目前我有一个脚本, 从帝联的 CDN 外链获取一下文件作为备份.
使用的是
Python 2.7.10
requests 2.8.1
目前碰到一个情况, 使用 requests 下载大文件的时候会出现下载文件不完整的情况, 出现的概率非常大, 应该不会是网络原因导致的. 相关代码概括如下:
requests.adapters.DEFAULT_RETRIES = 5
response = requests.get(url, stream=True)
status = response.status_code
if status == 200:
total_size = int(response.headers['Content-Length'])
with open('xxx', 'wb') as of:
for chunk in response.iter_content(chunk_size=102400):
if chunk:
of.write(chunk)
下载完毕后我会使用如下方式和上面的 total_size 进行对比
with open('xxx', 'r') as f:
if isinstance(f, file):
length = os.fstat(f.fileno()).st_size
if total_size == length:
True
else:
False
代码逻辑如上. 但是对于 100M 以上的文件, 几乎都是保存在本地的文件和获取的响应头里面的 content-length 不一致.
是我 requests 的用法不对吗? 还是有其他更好的办法可以保证文件能完整的下载呢?
P粉4512706452022-04-12 16:57:52
I found an article that can solve the problem of incomplete download of requests: https://www.jianshu.com/p/f92704c42b49
Mainly used response.raw.tell() and response .headers.get('Content-Length')
黄舟2017-04-17 17:10:56
The network is inherently unstable. It is normal for the network to be interrupted when downloading large files. As long as you have a certain probability of success, it may be a network problem.
The solution is to compare the size after downloading and resume the download if it is incomplete. Reference: Writing breakpoint resume download software in python
Another method is to call a download tool such as curl that supports resumed downloads.
黄舟2017-04-17 17:10:56
Has the poster solved this problem? I encountered the same problem, no errors were reported, and the download of several M files was incomplete. The usage is the same as yours