python - "for chunk in response.iter_content(1024)"引发 StreamConsumedError() 异常

标签 python python-2.7 exception python-requests

我不完全确定提出这个问题的最佳方式是什么,

但我正在编写一个脚本,使用 request.get() 从互联网下载一些内容,一切正常,但由于某种原因,现在引发了 StreamConsumedError() ,我不确定为什么。

Traceback (most recent call last):
File "./pythonDL-ver_0.0.4.py", line 90, in <module>
for chunk in response.iter_content(1024):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/models.py", line 766, in iter_content
raise StreamConsumedError()
requests.exceptions.StreamConsumedError

如果您需要更多信息,我可以添加它。谢谢。

while True:
    count = count + 1
    print 'testing ' + str(count) + '\n'
    print url
    url_2 = url.format(count = count)
    print '////' + str(url_2) + ' for loop ' + str(count) + "////\n"


    print str(url_2) + ' testing url \n'

    filename = posixpath.basename(url_2)
    print str(filename) + ' testing filename \n'
    response = requests.get(url_2, stream = True)
    responseString = str(response)

    print str(responseString) + 'testing res2 \n'

    if responseString == '<Response [404]>':
        print '......No more Requests......\n'
        break
    elif responseString == '<Response [200]>':
        print '......Successful Request....\n'
    else:
        break

    print responseString

    while responseString == '<Response [200]>':
        print 'testing while loop: ' + str(responseString)
        with open(filename, 'wb') as fp:
            for chunk in response.iter_content(1024):
                fp.write(chunk)

    count += 1
    print str(count) + ' = counting value'

这是停止工作的循环。

最佳答案

    while responseString == '<Response [200]>':
        print 'testing while loop: ' + str(responseString)
        with open(filename, 'wb') as fp:
            for chunk in response.iter_content(1024):
                fp.write(chunk)

此循环永远不会终止,一次 responseString<Response [200]>它永远如此,因为没有什么可以改变。

唯一阻止循环永远进行的事情是您可以多次读取流响应。因此,当循环再次尝试时,响应会抛出错误。

最简单的修复方法是替换 whileif

    if responseString == '<Response [200]>':
        with open(filename, 'wb') as fp:
            for chunk in response.iter_content(1024):
                fp.write(chunk)

关于python - "for chunk in response.iter_content(1024)"引发 StreamConsumedError() 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45379903/

相关文章:

python - Google App Engine 中的自定义身份验证

java - 如何验证 JUnit 测试中抛出的异常的详细信息?

python - 如何返回字母子串?

python - 将整数数组转换为字符串的最佳方法是什么?

python - 提交表单后,如何在点击所述元素之前等待元素加载? ( Selenium / python )

c++ - 什么是 R6010 错误?

exception - 为什么我的变量在 erlang try 中不安全?

python - 从数组列中删除重复项

python - 使用生成器的二叉树中序遍历

python - 为什么 python 库(例如 imaplib)不使用日志记录而是使用 sys.stderr.write?