This article is a tutorial on how to download YouTube videos using Python and a few libraries.
pip install pypiwin32 pytube
import win32clipboard
from pytube import YouTube
While surfing through Youtube videos, if you wish to download the video, you don’t have to go to a 3rd party website or change the URL, you just need to launch a batch file from your computer, which can be configured to run using shortcut keys.
For the above, we need to copy the URL. When we copy something on our machine, it gets saved into a clipboard. Similarly, if you copy the link to the YouTube video, this link will be stored on the clipboard.
#default link
link = "https://www.youtube.com/watch?v=gaPGpUU6jKQ"
try:
# get clipboard data
win32clipboard.OpenClipboard()
link = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
except Exception as ex:
print('Error : ',e)
exit()
We fetch the link from the clipboard using GetClipboardData() function provided by the win32clipboard module. Now that we have the link we can proceed to download the video.
try:
#where to save
SAVE_PATH = "PATH_TO_STORE_VIDEO"
yt = YouTube(link)
print('Title :',yt.title)
print('Available formats :')
for stream in yt.streams.all():
print(stream)
itag = input('\nEnter the itag number to download video of that format: ')
stream = yt.streams.get_by_itag(itag)
print('\nDownloading--- '+yt.title+' into location : '+SAVE_PATH)
stream.download(SAVE_PATH)
input('Hit Enter to exit')
except Exception as e:
print("Error",e) #to handle exception
input('Hit Enter to exit')
First, we create a variable and store the destination location of the download in it. We, then create the object of the ‘YouTube’ class we imported from ‘pytube’. For creating this object, we send the link to the YouTube video that we fetched from the clipboard.
The video can be downloaded in various formats. These formats can be fetched using streams.all() function. This lists all the available formats for the given video.
We then accept the ‘itag’ of the format in which the video needs to be downloaded. We fetch the stream of the given ‘itag’ and then download it using the ‘download()’ function. We send the download location of the video to this function as a parameter.
Snip of the YouTube video I wish to download
Snip of the output
I hope this article was helpful. Open to suggestions, do not hesitate to give your valuable feedback.
Thank you for reading!
#python #youtube