python - 在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))
推荐阅读
- jsf - 刷新 JSF 中的 UI 组件
- elasticsearch - 需要帮助将 ElasticSearch 过滤器布尔查询从 1.7 转换为 6.7
- shell - 在匹配的字符串之间循环(考虑一个数据集)然后控件应该移动到下一个数据集
- graphql - 从 Java 中的 GraphQL 查询中提取查询名称及其字段
- sql - SQL 查询:哪里 datetime = 过去 24 小时,怎么做?
- google-cloud-platform - MongoDB Atlas 与 GCP 对等现有集群
- javascript - 我想打印“2019 到 2020”,目前它显示 2019-04-01 到 2020-03-31
- python - 如何找到选择了表格的哪个项目?
- vb.net - 如何使用 VB.NET 将数组列表中的数据添加到 SQL Server 表中
- php - 从 twitter OAuth API 获取电子邮件 ID