Category: Notes in Python

The transformation of urllib2’s usage in Python3

Usage of urllib2 in Python

In Python, we can simply type the following code to import urllib2:

1
import urllib2

Then, urllib2.Request(host) and urllib2.urlopen(request) is available to use:

1
2
request = urllib2.Request(host)
response = urllib2.urlopen(request)

But, when it comes to Python3, a newer version of Python which has a lot differences with Python2, things gonna has to change!

Usage of urllib2 in Python3

In Python3, we cannot just type “import urllib2” to get it done, you’ll find an error message “No module named urllib2“. This is because of a different usage of urllib2 in python3. The following is my current solution:

Use the following code to import:

1
from urllib.request import Request

Then, here is how I use them:

1
2
request=Request(host)
response=urllib.request.urlopen(request)