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

问题描述

我正在尝试使用 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).register_on_progress_callback(on_progress) 替换为 yt_obj = YouTube(url) 时,一切正常,并且没有错误

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

解决方法

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

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 =======")
,

你的代码中的第一个问题是当一行

yt_obj = YouTube(url).register_on_progress_callback(on_progress)

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

第二个问题是这一行:

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

download() 函数返回 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}")

相关问答

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