使用带有 tqdm 进度条的 pafy 模块下载 YouTube 视频

问题描述

我正在尝试编写代码以使用 pafy 模块和使用 tqdm 模块的进度条从 YouTube 下载视频,但是进度条在下载完成之前已完成。

这是我的代码下载片段:

with tqdm.tqdm(desc=video_name,total=video_size,unit_scale=True,unit='B',initial=0) as pbar:
     bestVideo.download(filepath=full_path,quiet=True,callback=lambda _,received,*args: pbar.update(received))

这是进度条的图片

https://i.stack.imgur.com/VMBUN.png

解决方法

问题是因为 pbar.update() 期望值 current_received - previous_received

download 只给出 current_received 所以你必须使用一些变量来记住以前的值并减去它


最少的工作代码:

import pafy
import tqdm

# --- functions ---

previous_received = 0

def update(pbar,current_received):
    global previous_received
    
    diff = current_received - previous_received
    pbar.update(diff)
    previous_received = current_received

# --- main ---

v = pafy.new("cyMHZVT91Dw")
s = v.getbest()

video_size = s.get_filesize()
print("Size is",video_size)
    
with tqdm.tqdm(desc="cyMHZVT91Dw",total=video_size,unit_scale=True,unit='B',initial=0) as pbar:
     s.download(quiet=True,callback=lambda _,received,*args:update(pbar,received))

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...