Downloading videos from YouTube can be a useful task for personal use, offline viewing, or data analysis. One of the most efficient ways to download high-definition (HD) videos is by using the Python library yt-dlp
. This article walks you through the process of downloading YouTube videos in HD quality using Python and Google Colab.
Prerequisites
To begin, you need to set up a Google Colab environment. Google Colab allows you to run Python code in the cloud without the need for any setup on your local machine. You will also need to install the yt-dlp
library, which is an open-source tool used for downloading YouTube videos and other media from various websites.
Step-by-Step Guide
1. Installing yt-dlp
In the first step, we need to install the yt-dlp
library, which is an updated fork of the popular youtube-dl
library. yt-dlp
is faster and provides better features for video downloading.
To install yt-dlp
, you can use the following command in your Google Colab notebook:
!pip install yt-dlp
This will install the necessary library for downloading YouTube videos.
2. Importing the Required Libraries
Once yt-dlp
is installed, you can import it into your Python environment.
import yt_dlp
3. Writing the Python Function to Download YouTube Videos
Now, let’s write a Python function that will handle the video download. This function will accept the YouTube video URL and the path where you want to save the video.
def download_youtube_video(video_url, save_path="downloads"):
"""
Downloads a YouTube video in the best available video and audio quality.
Args:
video_url (str): URL of the YouTube video.
save_path (str): Directory to save the downloaded video.
"""
try:
# Options for yt-dlp
ydl_opts = {
'format': 'bestvideo+bestaudio/best', # Download best video and audio and merge
'outtmpl': f'{save_path}/%(title)s.%(ext)s', # Save file format
'merge_output_format': 'mp4', # Merge video and audio into MP4 format
}
# Downloading the video
print("Downloading...")
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([video_url])
print(f"Video downloaded successfully and saved in: {save_path}")
except Exception as e:
print(f"An error occurred: {e}")
Explanation of the Code
Let’s break down the code for downloading the video in HD quality:
-
Function Definition (
download_youtube_video
): This function takes two arguments:-
video_url
: The URL of the YouTube video you wish to download. -
save_path
: The directory where the downloaded video will be saved (default is "downloads").
-
-
Options Dictionary (
ydl_opts
):-
'format': 'bestvideo+bestaudio/best'
: This option ensures that the best available video and audio are downloaded and merged. -
'outtmpl': f'{save_path}/%(title)s.%(ext)s'
: This specifies the output template where the file will be saved. The video file will be named according to its title and extension (e.g., "my_video.mp4"). -
'merge_output_format': 'mp4'
: This tellsyt-dlp
to merge the video and audio streams into an MP4 format.
-
Downloading the Video: The
yt_dlp.YoutubeDL(ydl_opts)
is used to create a downloader object with the specified options. Thedownload([video_url])
method will download the video from the provided URL.Error Handling: If any errors occur during the download process, an exception is caught, and a message is displayed.
4. Running the Code
To execute the function, we need to provide the video URL and the directory to save the video. The following code allows you to input the video URL and the save path interactively:
if __name__ == "__main__":
# Input YouTube video URL
video_url = input("Enter the YouTube video URL: ").strip()
# Input save directory (default is 'downloads')
save_path = input("Enter the save path (or press Enter for default 'downloads'): ").strip() or "downloads"
# Call the function to download the video
download_youtube_video(video_url, save_path)
How It Works:
- User Input: The script prompts the user to enter the YouTube video URL and the save path.
-
Calling the Function: The
download_youtube_video
function is called with the provided URL and save path. - Downloading: The video is downloaded in HD quality and saved in the specified directory.
Running the Code in Google Colab
- Open a new Google Colab notebook.
- Install
yt-dlp
using the!pip install yt-dlp
command. - Copy and paste the Python code into the notebook.
- Run the code. When prompted, enter the YouTube video URL and the save directory.
Conclusion
By following the steps above, you can easily download YouTube videos in HD quality using Python and Google Colab. This process uses the yt-dlp
library, which is a powerful tool for downloading high-quality video and audio from YouTube and many other websites.
Feel free to modify the code to suit your needs, such as adding additional options or customizing the file-saving path. Happy coding!
Author Credits:
For Non-Coders
Fully Tested Code - Copy & Paste to Google Colab - Free
!pip install yt-dlp
import yt_dlp
def download_youtube_video(video_url, save_path="downloads"):
"""
Downloads a YouTube video in the best available video and audio quality.
Args:
video_url (str): URL of the YouTube video.
save_path (str): Directory to save the downloaded video.
"""
try:
# Options for yt-dlp
ydl_opts = {
'format': 'bestvideo+bestaudio/best', # Download best video and audio and merge
'outtmpl': f'{save_path}/%(title)s.%(ext)s', # Save file format
'merge_output_format': 'mp4', # Merge video and audio into MP4 format
}
# Downloading the video
print("Downloading...")
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([video_url])
print(f"Video downloaded successfully and saved in: {save_path}")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
# Input YouTube video URL
video_url = input("Enter the YouTube video URL: ").strip()
# Input save directory (default is 'downloads')
save_path = input("Enter the save path (or press Enter for default 'downloads'): ").strip() or "downloads"
# Call the function to download the video
download_youtube_video(video_url, save_path) `
Top comments (0)