AttributeError: 'module' object has no attribute 'request'

PythonPython 3.xPython 3.3

Python Problem Overview


When I run the following code in Python 3.3:

import urllib
tempfile = urllib.request.urlopen("http://yahoo.com")

I get the following error:

enter image description here

I did this too to verify:

enter image description here

What am I doing wrong?

Python Solutions


Solution 1 - Python

The urllib module has been split into parts and renamed in Python 3 to urllib.request, urllib.parse, and urllib.error.


Import urllib.request instead of urllib.

import urllib.request

Solution 2 - Python

Interestingly, I noticed some IDE-depending behavior.

Both Spyder and PyCharm use the same interpreter on my machine : in PyCharm I need to do

> import urllib.request

while in Spyder,

> import urllib

does fine

Solution 3 - Python

If this is on PyCharm, as was mine, make sure your file name isn't urllib.py.

Solution 4 - Python

  • In visual code , u have to write import urllib.request instead of just import urllib.
  • Also, whenever errors such as module x has no attribute y occurs, it's because you have named the current file same as the package you are trying to import.
  • So, the way import in python works is that it first searches the current dir, and if it finds the module/package 'x' u were looking for , it assumes that it has found the target file, and searches for 'y'. And since u haven't defined 'y', the aforementioned error occurs.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPruthvi RajView Question on Stackoverflow
Solution 1 - PythonfalsetruView Answer on Stackoverflow
Solution 2 - PythonJB LepetitView Answer on Stackoverflow
Solution 3 - PythonAnonymous PersonView Answer on Stackoverflow
Solution 4 - PythonAshrafView Answer on Stackoverflow