How to Download YouTube Video with youtube_dl in Python

09/09/2021

Contents

In this article, you will learn how to download YouTube video with youtube_dl in Python.

Download YouTube Video with youtube_dl

youtube-dl is a command-line program to download videos from YouTube.com and a few more sites. It requires the Python interpreter (2.6, 2.7, or 3.2+), and it is not platform-dependent.

In Python, the youtube_dl library provides a convenient way to use the functionality of youtube-dl in your own Python scripts and projects. The library provides a high-level API to download videos and extract information from YouTube and other video hosting sites.

To download a YouTube video using the youtube_dl library in Python, you can use the following code:

import youtube_dl

ydl_opts = {
    'format': 'bestaudio/best',
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '192',
    }],
}

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

Replace <video_id> with the actual id of the YouTube video you want to download. The code above downloads the audio from the video in MP3 format with a quality of 192kbps.

You can change the format to any other supported format, such as video formats like MP4, FLV, 3GP, etc. You can also extract other information from the video, such as its title, description, and uploaded date, by adding the appropriate options to the ydl_opts dictionary.

Here is an example of how to download the video in MP4 format and extract its title:

import youtube_dl

ydl_opts = {
    'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
    'outtmpl': '%(title)s.%(ext)s',
    'noplaylist': True,
}

with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    info_dict = ydl.extract_info('https://www.youtube.com/watch?v=', download=False)
    video_title = info_dict.get('title', None)
    if video_title:
        print(f'Video title: {video_title}')
    ydl.download(['https://www.youtube.com/watch?v='])

In this example, the outtmpl option is used to specify the output template for the downloaded file name. The %(title)s and %(ext)s placeholders are replaced with the actual title of the video and its file extension, respectively. The noplaylist option is used to download only the video and not the entire playlist.

You can also use the extract_info method to extract information from the video without downloading it. The method returns a dictionary with various information about the video, such as its title, description, and uploaded date. The download parameter is set to False to only extract the information and not download the video.