ImportError : cannot import name urlopen

42,012

Solution 1

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()

Solution 2

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.

Share:
42,012
plzhelp
Author by

plzhelp

Updated on February 20, 2020

Comments

  • plzhelp
    plzhelp about 4 years

    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

    • sahutchi
      sahutchi almost 8 years
      It works for me. Can you run import urllib2; print urllib2.__version__
    • sahutchi
      sahutchi almost 8 years
      Actually, another question too - are you using python 2 or 3?
    • dmlicht
      dmlicht almost 8 years
      urllib2 is in the python standard library, so you shouldn't have to pip install it.
    • plzhelp
      plzhelp almost 8 years
      Is there another way to solve the error? :/
    • dmlicht
      dmlicht almost 8 years
      I'm thinking about it. You could upgrade to python 3 :P
    • dmlicht
      dmlicht almost 8 years
      Are you absolutely sure you're running 2.7.12? Can you run your code with import sys; print(sys.version) and verify the output?
    • plzhelp
      plzhelp almost 8 years
      I got "2.7.12 <v2.7.12:d33e0cf91556....>[MSC v1.500 64 bit...]
  • sahutchi
    sahutchi almost 8 years
    Further research is that this was answered here: stackoverflow.com/questions/2792650/…