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('\r',
f'《 {file_name} 》:%.2fMB\t' % (content_size / 1024 / 1024),
'下载进度:[%-50s%.2f%%]耗时:%.1fs' % (
'>' * int(50 * percentage), percentage * 100, time.time() - start_time),
end='')
except Exception as e:
print('下载出错', e)