您现在的位置是:网站首页 > 博客日记 >

python文件流式下载|带进度条

作者:yxn 阅读量:80 发布日期:2023-11-21

import requests
from tqdm import tqdm

url = 'https://yixiuna.top/a.mp3'

# 发起GET请求,获取MP3文件流
response = requests.get(url, stream=True)

# 获取文件大小
total = int(response.headers['Content-Length'])
# or
# total = int(requests.head(url).headers['Content-Length'])  # 发起HEAD请求,获取文件大小

# 判断是不是 音乐文件
res_type = set(response.headers.get('Content-Type').split(';'))
if not (res_type & {'audio/mpeg', 'audio/mp3'}):
    print("不是音乐文件")
    exit()

if response.status_code == 200:
    with open('周深-大鱼.mp3', 'wb') as file:
        # 使用tqdm创建进度条
        with tqdm(total=total, unit='iB', unit_scale=True, unit_divisor=1024, desc="正在下载:") as bar:
            for chunk in response.iter_content(chunk_size=102400):
                if chunk:
                    file.write(chunk)
                    bar.update(len(chunk))  # 更新进度条
    print("文件下载完成")
else:
    print("请求失败,状态码:", response.status_code)

yxn

2023-11-21