问题描述
我去过多个论坛,并且阅读了文档。我仍然不知道如何使这项工作。
在下载视频时如何显示进度?我需要提供参数吗?我看到很多人在做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()
仅使用三个参数(stream
,chunk
和bytes_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()