38
votes

I have tried

import urllib.request

or

import urllib

The path for my urllib is /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/__init__.py

I am wondering where is urlopen, or is my python module pointing to the wrong file?

6
Funny. Works for me (and I have the same path). What do you get from os.listdir(os.path.dirname(urllib.__file__))? - mgilson
That's ['__init__.py', '__pycache__', 'error.py', 'parse.py', 'request.py', 'response.py', 'robotparser.py'] - user1999806
it does sound like your paths are crossed. try import sys;print(sys.path) and see if any python 2 related paths appear? if so, perhaps you've got something unusual set in your PYTHONPATH in your shell environment? - ben author
And, for the record, import urllib.request; urllib.request.urlopen works fine for me. import urllib; urllib.request.urlopen would raise the AttributeError that you are seeing. - mgilson
Somehow this worked guys... import urllib; from urllib.request import urlopen which is kind of odd but it worked! - user1999806

6 Answers

94
votes

According to this, you have to use the following:

import urllib.request

The reason is:

With packages, like this, you sometimes need to explicitly import the piece you want. That way, the urllib module doesn't have to load everything up just because you wanted one small part.

16
votes

Use this way

import urllib.request
urllib.request.urlopen('http://216.58.192.142',timeout=1)
5
votes

In python 3.6.x this worked for me, this way I did not have to change the code at all:

import urllib.request as urllib
2
votes

If nothing above worked for you, try renaming your python module.

In my particular case, the issue was that the file I was running was called http.py. Once I changed the name to test-http.py, importing urllib.request resolved the error AttributeError: module 'urllib' has no attribute 'request'

I had noticed that further up the exception trace the internal packages were trying to fetch a module called http, so guessing my module's name was wonkin stuff up...

0
votes

I had the same issue. I'm using Python 3.8.2.

I checked the _init_.py file located at /usr/lib/python3.8/urllib/ and its empty, which means you can not make a fully qualified access using only import urllib. In this case, you have to use import urllib.request.

-1
votes
import urllib.request as urllib

then in the code call urlopen function

example:

test = urllib.urlopen("----")