requests 下载大文件

发布时间 2023-07-06 17:07:50作者: boye169
# -*- coding: utf-8 -*-
from contextlib import closing
from requests import get
url = 'https://www.test.video/aa'
# 但是使用with语句的时候是需要条件的,任何对象,只要正确实现了上下文管理,就可以使用with语句,实现上下文管理是通过__enter__和__exit__这两个方法实现的
with closing(get(url,  stream=True)) as response:
    chunk_size = 1024  # 单次请求最大值
    # response.headers['content-length']得到的数据类型是str而不是int
    content_size = int(response.headers['content-length'])  # 文件总大小
    data_count = 0  # 当前已传输的大小
    with open('文件名.mp4', "wb") as file:
        for data in response.iter_content(chunk_size=chunk_size):
            file.write(data)
            done_block = int((data_count / content_size) * 50)
            # 已经下载的文件大小
            data_count = data_count + len(data)
            # 实时进度条进度
            now_jd = (data_count / content_size) * 100
            ## %% 表示%
            print("\r [%s%s] %d%% " % (done_block * '█', ' ' * (50 - 1 - done_block), now_jd), end=" ")