python - 如何在Python中下载文件时制作进度条

标签 python python-3.x python-requests python-3.6 tqdm

我正在使用 tqdm 来监视 python 程序中文件的下载,但它不显示进度条。 我有这个代码:

from tqdm import *
import requests
url = "https://as2.cdn.asset.aparat.com/aparat-video/520055aa72618571e4ce34b434e328b615570838-144p__58945.mp4"
name = "video"
with requests.get(url, stream=True) as r:
    r.raise_for_status()
    with open(name, 'wb') as f:
        for chunk in tqdm(r.iter_content(chunk_size=8192), r.headers.get("content-length")):
            if chunk:  # filter out keep-alive new chunks
                f.write(chunk)
                # f.flush()

但是当我运行它时,它不会向我显示进度条,而是向我显示以下内容:

763499: 94it [00:00, 192.31it/s]

我也尝试过这段代码:

from tqdm import *
import requests
url = "https://as2.cdn.asset.aparat.com/aparat-video/520055aa72618571e4ce34b434e328b615570838-144p__58945.mp4"
name = "asdasdjk"
with requests.get(url, stream=True) as r:
    r.raise_for_status()
    with open(name, 'wb') as f:
        for chunk, bar in r.iter_content(chunk_size=8192), r.headers.get("content-length"),tqdm(range(0,int(r.headers.get("content-length")))):
            if chunk:  # filter out keep-alive new chunks
                f.write(chunk)
                # f.flush()

但它给了我错误:

Exception has occurred: ValueError
too many values to unpack (expected 2)
  File "test.py", line 8, in <module>
    for chunk, bar in r.iter_content(chunk_size=8192), r.headers.get("content-length"),tqdm(range(0,int(r.headers.get("content-length")))):

最佳答案

from tqdm import *
import requests
url = "https://as2.cdn.asset.aparat.com/aparat-video/520055aa72618571e4ce34b434e328b615570838-144p__58945.mp4"
name = "video"
with requests.get(url, stream=True) as r:
    r.raise_for_status()
    with open(name, 'wb') as f:
        pbar = tqdm(total=int(r.headers['Content-Length']))
        for chunk in r.iter_content(chunk_size=8192):
            if chunk:  # filter out keep-alive new chunks
                f.write(chunk)
                pbar.update(len(chunk))

关于python - 如何在Python中下载文件时制作进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59470907/

相关文章:

python - 如何将自己分配给自己的另一个实例

python - 从label_image绘制轮廓

python - 在 Python 中加密数据 -

python - 使用 PIL 从 True/False 值列表中写入颜色 block

python - 从 url 文本自动生成文件名

python 3 从json字典中获取特定值

python - 尽管所有图像都可下载,但请求无法从某个站点下载任何图像?

python - python中的分组列表元素

python - 使用 r2pipe 进行多处理

python - 如何在python中返回一个空列表