Search code examples
python-3.ximporturllib2

`No module named 'urllib2' - how do i use it in Python so I can make a Request


Python newbie and just not sure what to do for python

I want to use urllib2 - Request to make a call How can I do that, for example in the repl. I can't figure out the right way

$ python3
Python 3.7.3 (default, Apr  3 2019, 05:39:12) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from urllib2 import Request, urlopen, URLerror, HTTPerror
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'urllib2'
>>> from urllib2 import Request, urlopen, URLerror, HTTPerror
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'urllib2'
>>> import Request
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'Request'
>>> import urllib2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'urllib2'
>>> 

...
req = Request(URL, json_message) #(URL and json_message defined but not shown here)

...

Do I have to install urllib2 into the system separately or something. Like I said just a Python newbie not knowing steps and syntax. thanks!

The example I am working from has

from urllib2 import Request, urlopen, URLError, HTTPError

and then uses Request(... but when I try that in a python3 repl I get

$ python3
Python 3.7.3 (default, Apr  3 2019, 05:39:12) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from urllib2 import Request
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'urllib2'
>>> 

Solution

  • There is no urllib2 in python3; see this question for more details. (The short version of the backstory here is that Python2 and Python3 are entirely different types of flying altogether; not all stdlib libraries in Py2 are available in Py3.)

    Instead, try urllib (similar API);

    from urllib import request
    

    You can hit the urllib documentation here, which may help.