How to download Youtube Music and Videos with Python

shittu_olumide_

Shittu Olumide

Posted on February 7, 2023

How to download Youtube Music and Videos with Python

This article will discuss how to easily download music and videos from Youtube using the Python programming language. The reason why we will be using Python is that it is a lightweight, fast and easy tool to use for software development.

We will be using two libraries so as to achieve our aim argparse and pytube , it can be installed using the python package installer (pip).

Importing the libraries

import argparse
from pytube import YouTube
Enter fullscreen mode Exit fullscreen mode

To parse the arguments supplied to the script, we'll use argparse, and to download YouTube videos, we'll use pytube.

Next, we must provide the folders in which the video and audio should be stored. I do this by using the following constants:

VIDEO_DOWNLOAD_DIR = "../Downloads/videos"
AUDIO_DOWNLOAD_DIR = "..Downloads/audio"
Enter fullscreen mode Exit fullscreen mode

Download function

Let's write a function that takes care of downloading the videos and audio in their respective folders separately.

For audio, we will filter the streams for audio-only content, choose the first one that is available, and download the audio-only stream to the AUDIO_DOWNLOAD_DIR directory.

def YoutubeAudioDownload(video_url):
    video = YouTube(video_url)
    audio = video.streams.filter(only_audio = True).first()

    try:
        audio.download(AUDIO_DOWNLOAD_DIR)
    except:
        print("Failed to download audio")

    print("audio was downloaded successfully")
Enter fullscreen mode Exit fullscreen mode

For the video, the function takes the URL of the YouTube video and downloads the best/highest resolution available to the VIDEO_DOWNLOAD_DIR directory.

def YoutubeVideoDownload(video_url):
    video = YouTube(video_url)
    video = video.streams.get_highest_resolution()

    try:
        video.download(VIDEO_DOWNLOAD_DIR)
    except:
        print("Unable to download video at this time!")

    print("Video downloaded!")
Enter fullscreen mode Exit fullscreen mode

These two simple functions take the YouTube video and audio URL, download it in the greatest resolution possible, and then save it in their respective directory, but if there is an error, it prints out an error message.

Main function

The video URL is parsed using argparse in the main function, and an optional audio-only flag is also used. The video's audio will be downloaded if the flag is enabled; by default, both the video and audio are downloaded.

These two simple functions take the YouTube video and audio URL, download it in the greatest resolution possible, and then save it in their respective directory, but if there is an error, it prints out an error message.

Let's have a look at the code.

if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("-v", "--video", required = True, help = "Youtube video URL")
    ap.add_argument("-a", "--audio", required = False, help = "Audio only", action = argparse.BooleanOptionalAction)
    args = vars(ap.parse_args())

    if args["audio"]:
        YoutubeAudioDownload(args["video"])
    else:
        YoutubeVideoDownload(args["video"])
Enter fullscreen mode Exit fullscreen mode

And we are done!

To test the code out if it actually works, type the following in the terminal.

# for audio
python main.py -a -v "[YouTube video URL]"

# for videos
python main.py -v "[YouTube video URL]"
Enter fullscreen mode Exit fullscreen mode

The audio/video directory should have the necessary media downloaded.

Wrap up

In this article, we discussed how to easily download audio and video from Youtube, using the pytube library. We also used the argparse library to add arguments to the terminal so that we can download the media with shorthand and links to either the audio or video. I personally use this to download songs that I like, and it works perfectly.

Let’s connect: Twitter & LinkedIn

You can also check out my Youtube channel.

Happy coding! 😊

💖 💪 🙅 🚩
shittu_olumide_
Shittu Olumide

Posted on February 7, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related