简体   繁体   English

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

[英]AttributeError: 'module' object has no attribute 'request'

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:我收到以下错误:

在此处输入图片说明

I did this too to verify:我也这样做来验证:

在此处输入图片说明

What am I doing wrong?我究竟做错了什么?

The urllib module has been split into parts and renamed in Python 3 to urllib.request , urllib.parse , and urllib.error . urllib模块已被拆分为多个部分,并在 Python 3 中重命名为urllib.requesturllib.parseurllib.error


Import urllib.request instead of urllib .导入urllib.request而不是urllib

import urllib.request

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很好

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM