gpt4 book ai didi

尝试下载文件时,Python 请求抛出 Connection Broken : ChunkedEncodingError with http. client.IncompleteRead

转载 作者:行者123 更新时间:2023-12-04 04:24:18 25 4
gpt4 key购买 nike

我正在尝试使用请求模块下载 PDF 文件,代码如下:

import requests

url = "<url of the pdf>"
r = requests.get(url, stream=True, timeout=(60, 120), headers={'Connection': 'keep-alive','User-Agent': 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10136'})

print(r.headers)
print(r.status_code)

try:
with open('blah.pdf', 'wb') as f:
for chunk in r:
# print(chunk)
f.write(chunk)
except Exception as e:
print(e)

输出如下:

{'Cache-Control': 'private', 'Transfer-Encoding': 'chunked', 'Content-Type': 'application/pdf', 'Server': 'Microsoft-IIS/7.5', 'X-AspNet-Version': '4.0.30319', 'X-Powered-By': 'ASP.NET', 'Date': 'Wed, 02 Oct 2019 05:17:11 GMT', 'Set-Cookie': 'bbb=rd102o00000000000000000000ffff978433aao80; path=/; Httponly; Secure'}
200
('Connection broken: IncompleteRead(0 bytes read, 2 more expected)', IncompleteRead(0 bytes read, 2 more expected))

这是完整的堆栈跟踪:

Traceback (most recent call last):
File "/storage/anaconda3/lib/python3.7/site-packages/urllib3/response.py", line 425, in _error_catcher
yield
File "/storage/anaconda3/lib/python3.7/site-packages/urllib3/response.py", line 755, in read_chunked
chunk = self._handle_chunk(amt)
File "/storage/anaconda3/lib/python3.7/site-packages/urllib3/response.py", line 709, in _handle_chunk
self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.
File "/storage/anaconda3/lib/python3.7/http/client.py", line 612, in _safe_read
raise IncompleteRead(b''.join(s), amt)
http.client.IncompleteRead: IncompleteRead(0 bytes read, 2 more expected)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/storage/anaconda3/lib/python3.7/site-packages/requests/models.py", line 750, in generate
for chunk in self.raw.stream(chunk_size, decode_content=True):
File "/storage/anaconda3/lib/python3.7/site-packages/urllib3/response.py", line 560, in stream
for line in self.read_chunked(amt, decode_content=decode_content):
File "/storage/anaconda3/lib/python3.7/site-packages/urllib3/response.py", line 781, in read_chunked
self._original_response.close()
File "/storage/anaconda3/lib/python3.7/contextlib.py", line 130, in __exit__
self.gen.throw(type, value, traceback)
File "/storage/anaconda3/lib/python3.7/site-packages/urllib3/response.py", line 443, in _error_catcher
raise ProtocolError("Connection broken: %r" % e, e)
urllib3.exceptions.ProtocolError: ('Connection broken: IncompleteRead(0 bytes read, 2 more expected)', IncompleteRead(0 bytes read, 2 more expected))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "test.py", line 12, in <module>
for chunk in r:
File "/storage/anaconda3/lib/python3.7/site-packages/requests/models.py", line 753, in generate
raise ChunkedEncodingError(e)
requests.exceptions.ChunkedEncodingError: ('Connection broken: IncompleteRead(0 bytes read, 2 more expected)', IncompleteRead(0 bytes read, 2 more expected))

当我在 Google Chrome 等网络浏览器上打开该 pdf 时,chrome 的内置 pdf 插件可以正确加载它,并且可以在浏览器上阅读。但是,如果我尝试通过单击下载图标来下载它,我会收到 Failed - Network Error Firefox 无法加载/下载它。 (Firefox 和 Chrome 都升级到最新版本)当我在 Windows 机器上测试它时,Microsoft edge 能够下载 pdf ......

上面的代码,如果我用其他一些 pdf 来测试它,比如这个: https://adobe.com/content/dam/acom/en/accessibility/products/acrobat/pdfs/acrobat-x-accessibility-checker.pdf
效果很好。

我尝试了一些命令行工具,例如 curl、wget、aria2c(设置了正确的 header ,如浏览器请求)都无法下载 pdf。

wget 输出:

connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [application/pdf]
Saving to: ‘blah.pdf’

<pdf_url> [ <=> ] 101.68K 66.1KB/s in 1.5s

2019-10-02 11:29:50 (69.1 KB/s) - Read error at byte 108786 (Success).

使用 wget 下载的文件已损坏。

我尝试过的另一件事是使用 mitm 和 chromedriver+selenium 组合来检查它。

自动 chrome 浏览器无法加载 pdf 并显示错误:

502 Bad Gateway
HttpSyntaxException('Malformed chunked body',)

如何使用 requests 模块下载此 pdf?非常感谢任何帮助。

最佳答案

几天后我解决了这个问题。服务器未正确关闭连接,因此 python 库抛出 IncompleteReadError。我设法使用安装在系统中的 curl 使用参数 --compressed 和所有必要的 header 下载它:

from subprocess import call

pdf_url = ""
pdf_filename = ""
call(["curl", pdf_url,
'-H', 'Connection: keep-alive',
'-H', 'Cache-Control: max-age=0',
'-H', 'Upgrade-Insecure-Requests: 1',
'-H', 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36',
'-H', 'Sec-Fetch-Mode: navigate',
'-H', 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
'-H', 'Sec-Fetch-Site: cross-site',
'-H', 'Accept-Encoding: gzip, deflate, br',
'-H', 'Accept-Language: en-US,en;q=0.9,bn;q=0.8',
'-H', 'Cookie: bbb=rd102o00000000000000000000ffff978432aao80',
'--compressed', '--output', pdf_filename])

使用 call subprocess 的方法模块。即使 curl 显示如下错误消息:

curl: (18) transfer closed with outstanding read data remaining

但是,下载的 pdf 可以使用任何 pdf 查看器打开。

关于尝试下载文件时,Python 请求抛出 Connection Broken : ChunkedEncodingError with http. client.IncompleteRead,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58195791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com