Professional Documents
Culture Documents
This article is a tutorial on how to download YouTube videos using Python and a few libraries.
Requirements:
1. Python 3.0
2. Pip
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()
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)
itag = input('\nEnter the itag number to download video of that format: ')
stream = yt.streams.get_by_itag(itag)
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.
Let’s create a batch file that we can run whenever we wish to download the video.
1. Go to the folder where our Python script resides.
2. Create a batch file ‘ytDownloader.bat’.
3. Edit with Notepad →python NAME_OF_PY_SCRIPT.py
4. Save this batch(.bat) file.
We copy the URL of the YouTube video and run our batch file.
Snip of the output
I hope this article was helpful. Open to suggestions, do not hesitate to give your valuable feedback.