Computers & Internet

Downloading YouTube Video Using Python

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.

  1. Start the terminal.
  2. Create a directory to house your project code inside. The sample directory structure is shown below.
  3. 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
  4. 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.
  5. 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.
  6. 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.
  7. 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, shell=True)

download_youtube_video('', '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, shell=True)

download_youtube_video_as_mp3('', 'output.mp3')