register_on_progress_callback() pytube 模块的方法导致问题

register_on_progress_callback() method of pytube module causing problem

我正在尝试使用 pytube 制作带有 youtube 视频进度条的下载器,但我遇到了一个错误。

我的代码:

from pytube import YouTube 

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)

url = "https://www.youtube.com/wat
ch?v=XQZgdHfAAjI&list=PLec973iciX1S0bLNOdmIejMVnUnBWpIwz"

yt_obj = YouTube(url).register_on_progress_callback(on_progress)

stream = yt_obj.streams.filter(progressive=True).get_highest_resolution().download()
size = stream.filesize
print(f"file size is {size}")

当我运行这段代码时,我得到以下错误:

Traceback (most recent call last):
  File "pytube_progress.py", line 15, in <module>
    stream = yt_obj.streams.filter(progressive=True).get_highest_resolution().download()
AttributeError: 'NoneType' object has no attribute 'streams'

有趣的是,当我用 yt_obj = YouTube(url) 替换这行代码时:yt_obj = YouTube(url).register_on_progress_callback(on_progress) 一切正常,没有错误。

可以找到 register_on_progress_callback() 函数的文档 here

您的代码中的第一个问题是行

yt_obj = YouTube(url).register_on_progress_callback(on_progress)

被执行,因为 register_on_progress_callback() 没有 return 任何东西,变量 yt_obj 被赋值 None。然后,当您稍后在代码中有 yt_obj.streams 时,会触发 AttributeError.

第二个问题与这一行有关:

stream = yt_obj.streams.filter(progressive=True).get_highest_resolution().download()

download() 函数 return 是 str,而不是 Stream

这是您的代码的工作版本,解决了这两个问题:

from pytube import YouTube

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)

url = "https://www.youtube.com/watch?v=XQZgdHfAAjI&list=PLec973iciX1S0bLNOdmIejMVnUnBWpIwz"

# Create the YouTube object first
yt_obj = YouTube(url)

# Then register the callback
yt_obj.register_on_progress_callback(on_progress)

# Download the video, getting back the file path the video was downloaded to
file_path = yt_obj.streams.filter(progressive=True).get_highest_resolution().download()
print(f"file_path is {file_path}")

这也行得通,请注意您只会看到一次进度条,因为您第二次 运行 脚本时您已经下载了文件。

from pytube.cli import on_progress
from pytube import YouTube

url = "https://www.youtube.com/watch?v=DkU9WFj8sYo"

print("\n")

try:

    yt = YouTube(url, on_progress_callback=on_progress)
    yt.streams\
    .filter(file_extension='mp4')\
    .get_highest_resolution()\
    .download()

except EOFError as err:
    print(err)

else:
    print("\n====== Done - Check Download Dir =======")