download - python requests 下载大文件不完整
阿神
阿神 2017-04-17 17:08:56
0
3
949

目前我有一个脚本, 从帝联的 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 的用法不对吗? 还是有其他更好的办法可以保证文件能完整的下载呢?

阿神
阿神

闭关修行中......

reply all(3)
P粉451270645

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')

黄舟

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.

黄舟

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template