python 下载文件时如何制作进度条

How do I make progress bar while downloading file in python

我正在使用 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))