【问题标题】:urllib does not have the request attributeurllib 没有 request 属性
【发布时间】:2016-06-22 08:50:24
【问题描述】:

上周在我身上发生了几次,由于某种原因出现了 urllib。

req = urllib.request.Request(oauth_uri)
req.add_header('User-Agent', "Python client")
resp = urllib.request.urlopen(req, bytes_)
data = resp.read().decode("utf-8")

它起作用了,然后它说req = urllib.request.Request(oauth_uri) AttributeError: module 'urllib' has no attribute 'request',然后它突然出现,它又起作用了。

有谁知道这是怎么发生的以及如何解决它?我需要它运行可靠。

【问题讨论】:

  • 不是您问题的答案,但您可以考虑使用 requests 库。它非常易于使用,我从未遇到过任何问题。
  • 你导入了urllib.request吗?您需要使用import urllib.request,而不是import urllib
  • 这确实解决了问题,但为什么有时它会起作用,而其他时候却是它的裤子?
  • 这很奇怪。我唯一能想到的是你有时用 Python 2 运行它,或者 sometimes 某事正在做import some_lib as urllib

标签: python python-3.x urllib


【解决方案1】:

可能是 python 2/3 问题。确定你是用 python3 打开你的脚本吗?

查看this 相关问题。

编辑:

我认为 Carpetsmoker 想通了。这在这里有效:

import urllib.request

req = urllib.request.Request("http://example.com")
req.add_header('User-Agent', "Python client")
resp = urllib.request.urlopen(req)
data = resp.read().decode("utf-8")
print(data)

我不知道为什么它有时只起作用。也许你的代码中有一个微妙的错误?如果 python 突然“忘记”一个导入模块的属性,这似乎非常奇怪。

【讨论】:

  • 确切地说是在 3.5.1 中。目前我什至没有安装 2 个。
猜你喜欢
  • 2022-01-03
  • 2017-05-20
  • 2016-08-30
  • 2021-01-15
  • 2021-10-29
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
  • 2022-01-14
相关资源
最近更新 更多