Python 属性错误:';非类型';对象没有属性';内容';

Python 属性错误:';非类型';对象没有属性';内容';,python,python-requests,global-variables,zipfile,stringio,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.Con

我想用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“Connection Rejected”字符串。在这种情况下,没有必要尝试访问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!")

非常感谢。上面的错误消失了,但现在我总是被拒绝连接!!我试图在浏览器和命令行中打开该链接,但都成功了。检查是否有防火墙或网络配置阻止您访问该服务器。您是否可以在出现“连接被拒绝”错误的同一台机器上使用浏览器下载它?