Search code examples
pythonyoutubeundefinedpytubeyt

NameError: name 'yt' is not defined


I wrote this code to make a Python Video Downloader: from pytube import *

# 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!')

After I run it, it asks me to enter the link I want it to download, as I want it to do and after I enter the link, it shows me this error:

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

How do I fix it ???


Solution

  • You might be seeing the error because there might be some exception, may be you can initialize yt = None and then check whether it is not None and then can do different things.

    I was not able to reproduce your error, But I got a different error:

    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'
    

    You can resolve the filter issue by looking at Pytube 'YouTube' object has no attribute 'filter'