如何显示使用pytube下载YouTube视频的进度?

问题描述

我去过多个论坛,并且阅读了文档。我仍然不知道如何使这项工作。

在下载视频时如何显示进度?我需要提供参数吗?我看到很多人在做yt = YouTube(url,on_progress)时没有括号或参数,所以我很困惑。

我不知道file_handle应该是什么,我也不知道在哪里可以得到bytes_remaining

提前谢谢

def on_progress(stream,chunk,file_handle,bytes_remaining):
    total_size = stream.filesize
    bytes_downloaded = total_size - bytes_remaining
    percentage_of_completion = bytes_downloaded / total_size * 100
    print(percentage_of_completion)


def main():
    chunk_size = 1024
    url = "https://www.youtube.com/watch?v=GceNsojnMf0"
    yt = YouTube(url)
    video = yt.streams.get_highest_resolution()
    yt.register_on_progress_callback(on_progress(video,chunk_size,'D:\\Videos',video.filesize))
    print(f"Fetching \"{video.title}\"..")
    print(f"Fetching successful\n")
    print(f"information: \n"
          f"File size: {round(video.filesize * 0.000001,2)} MegaBytes\n"
          f"Highest Resolution: {video.resolution}\n"
          f"Author: {yt.author}")
    print("Views: {:,}\n".format(yt.views))

    print(f"Downloading \"{video.title}\"..")
    video.download('D:\\Videos')

解决方法

register_on_progress_callback()对象中的方法YouTube仅需要一个回调函数本身,而不是该函数的结果。您还需要更新函数on_progress的参数:方法register_on_progress_callback()仅使用三个参数(streamchunkbytes_remaining)。您可以像这样更新代码:

def on_progress(stream,chunk,bytes_remaining):
    total_size = stream.filesize
    bytes_downloaded = total_size - bytes_remaining
    percentage_of_completion = bytes_downloaded / total_size * 100
    print(percentage_of_completion)


def main():
    chunk_size = 1024
    url = "https://www.youtube.com/watch?v=GceNsojnMf0"
    yt = YouTube(url)
    video = yt.streams.get_highest_resolution()
    yt.register_on_progress_callback(on_progress)
    print(f"Fetching \"{video.title}\"..")
    print(f"Fetching successful\n")
    print(f"Information: \n"
          f"File size: {round(video.filesize * 0.000001,2)} MegaBytes\n"
          f"Highest Resolution: {video.resolution}\n"
          f"Author: {yt.author}")
    print("Views: {:,}\n".format(yt.views))

    print(f"Downloading \"{video.title}\"..")
    video.download('D:\\Videos')

main()

相关问答

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