Python AttributeError: 'module' 对象没有属性 'request'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22278993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:39:41  来源:igfitidea点击:

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

pythonpython-3.xpython-3.3

提问by Pruthvi Raj

When I run the following code in Python 3.3:

当我在 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?

我究竟做错了什么?

采纳答案by falsetru

Import urllib.requestinstead of urllib.

导入urllib.request而不是urllib.

import urllib.request

回答by JB Lepetit

Interestingly, I noticed some IDE-depending behavior.

有趣的是,我注意到了一些依赖于 IDE 的行为。

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

Spyder 和 PyCharm 在我的机器上使用相同的解释器:在 PyCharm 中我需要做

import urllib.request

导入 urllib.request

while in Spyder,

在 Spyder 时,

import urllib

导入 urllib

does fine

很好

回答by Anonymous Person

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

如果这是在 PyCharm 上,就像我的一样,请确保您的文件名不是 urllib.py。

回答by Ashraf

  • 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.
  • 在可视化代码中,你必须编写 import urllib.request 而不是 import urllib。
  • 此外,每当出现诸如模块 x 没有属性 y 之类的错误时,这是因为您已将当前文件命名为与您尝试导入的包相同。
  • 因此,python 中 import 的工作方式是首先搜索当前目录,如果找到了您正在寻找的模块/包 'x',则假定它已找到目标文件,并搜索 'y'。并且由于您尚未定义 'y',因此会发生上述错误。