【问题标题】:NameError: name 'yt' is not definedNameError:名称“yt”未定义
【发布时间】:2021-12-27 12:14:43
【问题描述】:

我编写了这段代码来制作 Python 视频下载器: 从 pytube 导入 *

# where to save
from pytube import YouTube

SAVE_PATH = "C:/Downloads"

# link of the video to be downloaded
link = input('Copy and paste your link here: ')

try:
    yt: YouTube = YouTube(link)
except:
    print("Connection Error")


mp4files = yt.filter('mp4')
yt.set_filename = input('What do u want to name it: ')
d_video = yt.get(mp4files[-1].extension, mp4files[-1].resolution)
try:
    d_video.download(SAVE_PATH)
except:
    print("Some Error!")
print('Task Completed!')

在我运行它之后,它要求我输入我希望它下载的链接,就像我希望它做的那样 在我输入链接后,它显示了这个错误:

mp4files = yt.filter('mp4')
NameError: name 'yt' is not defined

我该如何解决???

【问题讨论】:

  • 您正在点击except 语句,因此未创建yt 变量。当这种情况发生时,您需要有关您希望整个程序做什么的逻辑,例如退出?
  • 您在try 块中定义了yt,而不是作为全局变量。也许这就是你有这个问题的原因
  • 可能在您的错误消息中更明确。看起来它抓住了你不想要的东西。认为连接错误引发URLError

标签: python youtube undefined pytube yt


【解决方案1】:

您可能会看到错误,因为可能有一些异常,可能是您可以初始化yt = None,然后检查它是否不是 None ,然后可以做不同的事情。

我无法重现您的错误,但我得到了一个不同的错误:

Copy and paste your link here: https://www.youtube.com/watch?v=n4RjJKxsamQ
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-9-0d28f5939137> in <module>
     12
     13
---> 14 mp4files = yt.filter('mp4')
     15 yt.set_filename = input('What do u want to name it: ')
     16 d_video = yt.get(mp4files[-1].extension, mp4files[-1].resolution)

AttributeError: 'YouTube' object has no attribute 'filter'

您可以通过查看Pytube 'YouTube' object has no attribute 'filter' 来解决filter 问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    • 2021-04-15
    • 2019-01-26
    • 2021-10-05
    • 2017-08-16
    • 2019-08-18
    相关资源
    最近更新 更多