Can we download a video using Python? Yes, its easy to download a video on youtube using youtube-dl library. Basically we don’t really need API to download a video. All we need is just the videoId. Here is a sample code for downloading a video using python. In this article, we will also add a function where we can download all your latest liked video which of course requires an API request.
First you need to install youtube-dl library
pip install youtube-dl
Create a new python file and named it as download_video.py
Related Posts
Then paste this code:
import sys, youtube_dl
YOUTUBE_DL_DIR = sys.path[0]+'/'
These are the libraries we need. I assigned a global variable named YOUTUBE_DL_DIR. This is the directory where this python file is saved. So all the youtube downloaded videos will be saved on the same directory.
def download_video(videoId):
yvideo = ['https://www.youtube.com/watch?v='+videoId]
ydl_opts = {'outtmpl': YOUTUBE_DL_DIR+'%(id)s %(title)s'}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download(yvideo)
This will download the video and save it on our directory. The name format will be: %(id)s %(title)s. This means the filename will start with the videoId and next is the title. You can change this according to your likes. Below are some template samples.
- %(id)s
- %(title)s
- %(channel)s
- %(uploader)s — uploaders full name
- %(ext)s — file extension
Finally, paste the main function. Please remember, the videoId here is just a sample. You can change it. You can find the videoid on the Url. Example:
- https://www.youtube.com/watch?v=GaGACOtd5RY
- The video is GaGACOtd5RY
if __name__ == "__main__":
videoId = 't4y9kwUS-zA'
download_video(videoId)
Save it and run:
python download_video.py
It should download the youtube video.