urllib 没有请求属性

urllib does not have the request attribute

上周发生在我身上几次,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'然后它突然起作用,又起作用了。

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

可能是 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 突然 "forget" 导入模块的属性,这似乎非常奇怪。