Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImportError : cannot import name urlopen

I am trying to open up an URL for my project and here is my code:

from urllib2 import urlopen
page = urlopen("https://docs.python.org/3/howto/urllib2.html")
contents = page.read()

It's just a simple code for a demo however, when I run the codes, I got the following error "ImportError : cannot import name urlopen"

I tried to type "pip install urllib2" into CMD and got the following error as well "Could not find a version that satisfies the requirement urllib2...no matching distribution found for urllib2"

How do I solve this error as I'm using python 2.7.12 instead of python3

like image 849
plzhelp Avatar asked Jul 20 '16 03:07

plzhelp


2 Answers

I'm going to take an educated guess and assume you are using python3. In python3, urllib2 has been split into urllib.request and urllib.error. See note at the top of the urllib2 page. The function you are looking for is contained in urllib.request. Try the following:

from urllib.request import urlopen
page = urlopen("https://docs.python.org/3/howto/urllib2.html")
contents = page.read()
like image 147
dmlicht Avatar answered Nov 14 '22 22:11

dmlicht


The answer to this question breaks down into two sections. The solution differs based on if you are using python 2 or python 3.

In python 3 urllib2 is no longer used. Try using urllib.request.

In python 2 you may just have a bad install or old version of urllib2. Try pip install urllib2.

like image 25
sahutchi Avatar answered Nov 14 '22 20:11

sahutchi