【问题标题】:AttributeError: 'NoneType' object has no attribute 'content'AttributeError:“NoneType”对象没有属性“内容”
【发布时间】:2018-12-12 16:16:48
【问题描述】:

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

【问题讨论】:

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


    【解决方案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!")
    

    【讨论】:

    • 谢谢!上面的错误消失了,但现在我总是被拒绝连接!
    • 我试图在浏览器和命令行中打开该链接,并且都有效。检查是否有一些防火墙或网络配置阻止您访问该服务器。您可以在出现“连接被拒绝”错误的同一台机器上使用浏览器下载它吗?
    猜你喜欢
    • 2019-01-01
    • 2021-12-26
    • 2019-07-23
    • 2018-05-13
    • 2020-09-07
    • 2017-05-03
    • 2023-03-16
    • 2018-07-14
    • 2013-06-16
    相关资源
    最近更新 更多