属性错误: 'NoneType'对象没有属性'content'



我想使用 python 下载一个 zip 文件,我在运行以下代码时得到

import requests, zipfile, StringIO
zip_file_url = "http://www.blog.pythonlibrary.org/wp-content/uploads/2012/06/wxDbViewer.zip"
r = None
try:
r = requests.get(zip_file_url, stream=True)
except requests.exceptions.ConnectionError:
print "Connection refused"
z = zipfile.ZipFile(StringIO.StringIO(r.content))

我应该如何声明"r"?

你不应该声明 r。在python中,你不需要声明变量。

从您的问题中不清楚,但我敢打赌您的输出包括 que"连接被拒绝"字符串。在这种情况下,无需尝试访问 r.content:由于连接被拒绝,因此无法存在任何内容。只需执行适当的错误管理:

import requests, zipfile, StringIO
zip_file_url = "http://www.blog.pythonlibrary.org/wp-content/uploads/2012/06/wxDbViewer.zip"
try:
r = requests.get(zip_file_url, stream=True)
except requests.exceptions.ConnectionError:
print "Connection refused"
exit() # That's an option, just finish the program
if r is not None:
z = zipfile.ZipFile(StringIO.StringIO(r.content))
else:
# That's the other option, check that the variable contains
# a proper value before referencing it.
print("I told you, there was an error while connecting!")

最新更新