AttributeError: ‘ module’对象没有属性‘ request’

当我在 Python 3.3中运行以下代码时:

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

我得到以下错误:

enter image description here

我这样做也是为了核实:

enter image description here

我做错了什么?

99709 次浏览

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

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

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

  • 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.