AttributeError:“ NoneType”对象没有属性“ content”

时间:2018-07-04 09:12:47

标签: python python-requests global-variables zipfile stringio

我想使用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”?

1 个答案:

答案 0 :(得分:1)

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

您的问题尚不清楚,但我敢打赌,您的输出中包含“连接被拒绝”字符串。在这种情况下,无需尝试访问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!")