Downloading YouTube Video Using Python
The article will should you how easily can you download your YouTube videos as video as well as MP3/Audio files.
System Configuration:
OS: Ubuntu 22.04
Software Requirements:
Programming Language: Python 3
Python Module: youtube-dl
Environment Setup:
Let’s get started:
Before jumping into the code we’ll need to set up a robust environment with required libraries/modules.
- Start the terminal.
- Create a directory to house your project code inside. The sample directory structure is shown below.
- Inside your project directory, there will be two subdirectories. src to host the source code and venv to host the Python virtual environment. Create an ‘src’ directory yourself with appropriate commands or GUI. You can create a directory from a Linux terminal using mkdir command. E.g. > mkdir src
- You can create a virtual environment with the python -m command. It is Python 3-specific command, if you’re using older or any other flavor of Python you may need some other way to create your virtual environment. If you’re on Anaconda or something you may not need a virtual environment as everything will already be a part of the project setup with these tools.
- Use the command python -m venv venv to create a Python virtual environment. This will add a new directory in the current directory and set up a Python Virtual Environment inside a box.
- Activity the virtual environment with source venv/bin/activate. The command will work on Ubuntu. For Windows or another operating system, you may need to do some research to accomplish the task.
- Now you have all the basic system setup. You’re all set to get started with downloading YouTube videos as video and audio files using a Python program.
Directory Structure:
1. Download YouTube Video
Get the source code from this gist.
# Download YouTube video
import subprocess
def download_youtube_video(url, output_file):
cmd = 'youtube-dl ' + url + ' -o ' + output_file
subprocess.call(cmd, shell=True)
download_youtube_video('https://www.youtube.com/watch?v=srVPLrmlBJY', 'output.mp4')
2. Download YouTube Video as MP3
Get the source from this gist.
# Download YouTube video as MP3
import subprocess
def download_youtube_video_as_mp3(url, output_file):
cmd = 'youtube-dl -x --audio-format mp3 ' + url + ' -o ' + output_file
subprocess.call(cmd, shell=True)
download_youtube_video_as_mp3('https://www.youtube.com/watch?v=srVPLrmlBJY', 'output.mp3')