Download YouTube video using Python to a certain directory

I found out a really cool python module that allows you to download videos from youtube easily. TO install it:

pip install pytube

Now, You can download your video like this –

from pytube import YouTube
yt = YouTube("https://www.youtube.com/watch?v=n06H7OcPd-g")
yt = yt.get('mp4', '720p')
yt.download('/path/to/download/directory')

Boom, Now you can easily scrape such videos using Python easily; Now, We Drink!

Update 1:

Thanks to @Chiramisu’s comment, You can use the following one-liner to download the highest quality video:

YouTube('video_url').streams.first().download('save_path')

For Windows, please specify path with double backslashes ex:

YouTube('video_url').streams.first().download('C:\\Users\\username\\save_path')

Update 2:

If pytube doesn’t seem to work for you, try using youtube-dl:

pip install --upgrade youtube-dl

Now Download Videos:

from __future__ import unicode_literals
import youtube_dl

ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['https://www.youtube.com/watch?v=BaW_jenozKc'])

More info on ytdl in python here.

Leave a Comment