requests 使用 stream 流形式下载文件

requests stream=True

import time
import requests

download_url = ''
start_time = time.time()
file_name = 'video.mp4'  # 文件名称

# 以流形式下载文件
result = requests.get(download_url, stream=True)
size = 0  # 已下载文件的大小
chunk_size = 1024 * 1024  # 每次下载数据的大小:单位字节 1024:1KB 1024*1024:1MB
content_size = int(result.headers["content-length"])  # 文件总大小:单位字节
try:
    if result.status_code == 200:
        with open(file_name, 'wb') as video_file:
            # 当把get函数的stream参数设置成True时,它不会立即开始下载
            # 使用iter_content或iter_lines遍历内容或访问内容属性时才开始下
            # 每次下载chunk_size大小的内容写入文件
            for data in result.iter_content(chunk_size=chunk_size):
                video_file.write(data)
                size += len(data)  # 已下载文件的大小
                # 已完成的百分比
                percentage = size / content_size
                # 打印进度条
                print('
',
                      f'《 {file_name} 》:%.2fMB	' % (content_size / 1024 / 1024),
                      '下载进度:[%-50s%.2f%%]耗时:%.1fs' % (
                          '>' * int(50 * percentage), percentage * 100, time.time() - start_time),
                      end='')
except Exception as e:
    print('下载出错', e)







路漫漫其修远兮,吾将上下而求索

本文来自博客园,作者:纪宇-年华,转载请注明原文链接:https://www.cnblogs.com/jiyu-hlzy/p/15249689.html

原文地址:https://www.cnblogs.com/jiyu-hlzy/p/15249689.html