0% found this document useful (0 votes)
29 views

How To Download YouTube Playlist Using Python - by Ashutosh Krishna - Python in Plain English

This document provides instructions on how to use Python and the Pytube library to download an entire YouTube playlist in different resolutions. It explains the prerequisites, defines a download_playlist function, and includes code to iterate through the playlist videos, check resolutions, download video and audio streams separately, and merge them into a final video file.

Uploaded by

shri smru
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

How To Download YouTube Playlist Using Python - by Ashutosh Krishna - Python in Plain English

This document provides instructions on how to use Python and the Pytube library to download an entire YouTube playlist in different resolutions. It explains the prerequisites, defines a download_playlist function, and includes code to iterate through the playlist videos, check resolutions, download video and audio streams separately, and merge them into a final video file.

Uploaded by

shri smru
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

1/16/24, 10:18 PM How to Download YouTube Playlist Using Python | by Ashutosh Krishna | Python in Plain English

How to Download YouTube Playlist Using


Python
A tutorial on using the Pytube library in Python to download entire YouTube playlists
in various
Open in app resolutions, including the high-quality 2160p resolution. Sign up Sign in

Ashutosh Krishna Search


· Follow
Published in Python in Plain English
6 min read · May 2, 2023

Listen Share

YouTube is the world’s largest video-sharing platform with millions of videos


uploaded every day. Many times you come across a playlist of videos on YouTube
that you want to watch offline or save for future reference. However, downloading a
single video from YouTube is easy, but when it comes to downloading an entire
playlist, it can be a daunting task. In such cases, automating the process using
Python can save a lot of time and effort.

https://python.plainenglish.io/how-to-download-youtube-playlist-using-python-4e832989e017 1/17
1/16/24, 10:18 PM How to Download YouTube Playlist Using Python | by Ashutosh Krishna | Python in Plain English

In this tutorial, you will be using the Pytube library in Python to download entire
YouTube playlists in various resolutions, including the high-quality 2160p
resolution. Pytube is a lightweight library that allows easy access to YouTube videos
and metadata. With Pytube, we can easily extract video URLs, download videos, and
even extract audio from videos. So, let’s dive into the tutorial and learn how to
download a YouTube playlist using Python.

If you’re in a hurry, jump to the GitHub gist to get the code immediately.

Prerequisites
To follow this tutorial, you should have a basic understanding of Python
programming language, including installing Python packages using pip.

You will also need to install the Pytube library, which can be installed using pip.
Open a command prompt or terminal window and type the following command:

pip install pytube

Apart from Python and Pytube, you will also need to have FFmpeg installed on your
system. FFmpeg is a command-line tool used for handling multimedia files. It is
required for Pytube to be able to download videos in various resolutions. You can
download FFmpeg from the official website and follow the installation instructions
for your operating system.

Let’s Code It!


Roll up your sleeves, fire up your favorite code editor, and let’s get started!

https://python.plainenglish.io/how-to-download-youtube-playlist-using-python-4e832989e017 2/17
1/16/24, 10:18 PM How to Download YouTube Playlist Using Python | by Ashutosh Krishna | Python in Plain English

Import the Libraries


Let’s import the necessary libraries for the program to run correctly.

import os
import re
from pytube import Playlist, YouTube

The code imports the os module to handle operating system functionalities, re

module to handle regular expressions, and pytube module to download the YouTube
playlist.

Create the Function


Let’s define a function called download_playlist . The function takes two parameters;
the playlist URL and the desired video resolution.

def download_playlist(playlist_url, resolution):


playlist = Playlist(playlist_url)
playlist_name = re.sub(r'\W+', '-', playlist.title)

if not os.path.exists(playlist_name):
os.mkdir(playlist_name)

It first creates a new Playlist object using the Pytube library and extracts the name
of the playlist. It then checks if a folder with the same name exists in the current

https://python.plainenglish.io/how-to-download-youtube-playlist-using-python-4e832989e017 3/17
1/16/24, 10:18 PM How to Download YouTube Playlist Using Python | by Ashutosh Krishna | Python in Plain English

working directory. If not, it creates a new folder with the playlist name.

Note that the re.sub() function replaces any non-alphanumeric characters in the
playlist title with a hyphen ("-") character. We do so because folder and file names in
most file systems have restrictions on the characters they can contain.

Downloading the Videos


The Playlist object provides a videos property which is an iterable of YouTube

objects. You first iterate through the list of videos in the playlist using a for loop
and enumerate function.:

for index, v in enumerate(playlist.videos, start=1):


...

The start parameter set to 1 to start counting from 1 instead of 0 because you're
going to use the index in the filenames. Thus it makes sense to start from 1.

Next, create a YouTube object for each video using its watch URL, and specify to use
OAuth for authentication:

for index, v in enumerate(playlist.videos, start=1):


video = YouTube(v.watch_url, use_oauth=True)

Recently, there were several issues where PyTube was throwing a KeyError. The fix was to
use the use_oauth=True parameter. When you run the code for the first time, it will ask
you to login into your YouTube account.

Filter the available video streams to select the one with the desired resolution, and
get its filename:

for index, v in enumerate(playlist.videos, start=1):


video = YouTube(v.watch_url, use_oauth=True)
video_resolution = video.streams.filter(res=resolution).first()
video_filename = f"{index}. {video_resolution.default_filename}"

https://python.plainenglish.io/how-to-download-youtube-playlist-using-python-4e832989e017 4/17
1/16/24, 10:18 PM How to Download YouTube Playlist Using Python | by Ashutosh Krishna | Python in Plain English

Determine the full path and filename for the video file, and check if it already
exists. If it does, skip downloading this video and move on to the next one:

for index, v in enumerate(playlist.videos, start=1):


video = YouTube(v.watch_url, use_oauth=True)
video_resolution = video.streams.filter(res=resolution).first()
video_filename = f"{index}. {video_resolution.default_filename}"
video_path = os.path.join(playlist_name, video_filename)
if os.path.exists(video_path):
print(f"{video_filename} already exists")
continue

If the desired resolution is not available, download the video with the highest
resolution instead:

for index, v in enumerate(playlist.videos, start=1):


...
video_streams = video.streams.filter(res=resolution)

if not video_streams:
highest_resolution_stream = video.streams.get_highest_resolution()
video_name = highest_resolution_stream.default_filename
print(f"Downloading {video_name} in {highest_resolution_stream.resoluti
highest_resolution_stream.download(filename=video_path)

If the desired resolution is available, you don’t have to download it directly. If you do
so, the downloaded video won’t have sound. Instead, download both the video and
audio streams separately, and merge them using the FFmpeg library to create the
final video file. Finally, rename the merged file and delete the temporary video and
audio files:

for index, v in enumerate(playlist.videos, start=1):


...
video_streams = video.streams.filter(res=resolution)

if not video_streams:
...

https://python.plainenglish.io/how-to-download-youtube-playlist-using-python-4e832989e017 5/17
1/16/24, 10:18 PM How to Download YouTube Playlist Using Python | by Ashutosh Krishna | Python in Plain English

else:
video_stream = video_streams.first()
video_name = video_stream.default_filename
print(f"Downloading video for {video_name} in {resolution}")
video_stream.download(filename="video.mp4")

audio_stream = video.streams.get_audio_only()
print(f"Downloading audio for {video_name}")
audio_stream.download(filename="audio.mp4")

os.system("ffmpeg -y -i video.mp4 -i audio.mp4 -c:v copy -c:a aac final


os.rename("final.mp4", video_path)
os.remove("video.mp4")
os.remove("audio.mp4")

The video stream is initially downloaded as video.mp4 and the audio stream is
downloaded as audio.mp4 . Next, the ffmpeg command takes two input files
( video.mp4 and audio.mp4 ), copies the video codec from the input file and uses the
AAC codec for audio, and saves the output as final.mp4 . The output file is created by
merging the video and audio streams from the two input files.

After ffmpeg finishes processing, the final.mp4 is renamed video_path and the
video and audio stream files are deleted.

The download_playlist Function


At this point, you have completed the download_playlist function. It should look like
this:

def download_playlist(playlist_url, resolution):


playlist = Playlist(playlist_url)
playlist_name = re.sub(r'\W+', '-', playlist.title)

if not os.path.exists(playlist_name):
os.mkdir(playlist_name)

for index, v in enumerate(playlist.videos, start=1):


video = YouTube(v.watch_url, use_oauth=True)
video_resolution = video.streams.filter(res=resolution).first()
video_filename = f"{index}. {video_resolution.default_filename}"
video_path = os.path.join(playlist_name, video_filename)
if os.path.exists(video_path):
print(f"{video_filename} already exists")
continue

https://python.plainenglish.io/how-to-download-youtube-playlist-using-python-4e832989e017 6/17
1/16/24, 10:18 PM How to Download YouTube Playlist Using Python | by Ashutosh Krishna | Python in Plain English

video_streams = video.streams.filter(res=resolution)

if not video_streams:
highest_resolution_stream = video.streams.get_highest_resolution()
video_name = highest_resolution_stream.default_filename
print(f"Downloading {video_name} in {highest_resolution_stream.reso
highest_resolution_stream.download(filename=video_path)

else:
video_stream = video_streams.first()
video_name = video_stream.default_filename
print(f"Downloading video for {video_name} in {resolution}")
video_stream.download(filename="video.mp4")

audio_stream = video.streams.get_audio_only()
print(f"Downloading audio for {video_name}")
audio_stream.download(filename="audio.mp4")

os.system("ffmpeg -y -i video.mp4 -i audio.mp4 -c:v copy -c:a aac f


os.rename("final.mp4", video_path)
os.remove("video.mp4")
os.remove("audio.mp4")

print("----------------------------------")

A line of dashes is also printed after every iteration to separate each video as they
are downloaded.

Main Function
Let’s create the main function that takes input from the user for the playlist URL and
desired video resolution. It then calls the download_playlist function with the user's
inputs.

if __name__ == "__main__":
playlist_url = input("Enter the playlist url: ")
resolutions = ["240p", "360p", "480p", "720p", "1080p", "1440p", "2160p"]
resolution = input(f"Please select a resolution {resolutions}: ")
download_playlist(playlist_url, resolution)

Completed Code

https://python.plainenglish.io/how-to-download-youtube-playlist-using-python-4e832989e017 7/17
1/16/24, 10:18 PM How to Download YouTube Playlist Using Python | by Ashutosh Krishna | Python in Plain English

import os
import re
from pytube import Playlist, YouTube

def download_playlist(playlist_url, resolution):


playlist = Playlist(playlist_url)
playlist_name = re.sub(r'\W+', '-', playlist.title)

if not os.path.exists(playlist_name):
os.mkdir(playlist_name)

for index, v in enumerate(playlist.videos, start=1):


video = YouTube(v.watch_url, use_oauth=True)
video_resolution = video.streams.filter(res=resolution).first()
video_filename = f"{index}. {video_resolution.default_filename}"
video_path = os.path.join(playlist_name, video_filename)
if os.path.exists(video_path):
print(f"{video_filename} already exists")
continue

video_streams = video.streams.filter(res=resolution)

if not video_streams:
highest_resolution_stream = video.streams.get_highest_resolution()
video_name = highest_resolution_stream.default_filename
print(
f"Downloading {video_name} in {highest_resolution_stream.resolution}")
highest_resolution_stream.download(filename=video_path)

else:
video_stream = video_streams.first()
video_name = video_stream.default_filename
print(f"Downloading video for {video_name} in {resolution}")
video_stream.download(filename="video.mp4")

audio_stream = video.streams.get_audio_only()
print(f"Downloading audio for {video_name}")
audio_stream.download(filename="audio.mp4")

os.system(
"ffmpeg -y -i video.mp4 -i audio.mp4 -c:v copy -c:a aac final.mp4 -loglevel quiet -
os.rename("final.mp4", video_path)
os.remove("video.mp4")
os.remove("audio.mp4")

print("----------------------------------")

https://python.plainenglish.io/how-to-download-youtube-playlist-using-python-4e832989e017 8/17
1/16/24, 10:18 PM How to Download YouTube Playlist Using Python | by Ashutosh Krishna | Python in Plain English

if __name__ == "__main__":
playlist_url = input("Enter the playlist url: ")
resolutions = ["240p", "360p", "480p", "720p", "1080p", "1440p", "2160p"]
resolution = input(f"Please select a resolution {resolutions}: ")
download_playlist(playlist_url, resolution)

playlist_downloader.py hosted with ❤ by GitHub view raw

Using this script, you can download all the videos from a YouTube Playlist in all
supported resolutions (including 1080p and 2160p).
Enter the playlist url and the resolution you wish to download.
Make sure you have ffmpeg setup on your machine. Check the tutorial for the setup
guide.
You can download the videos in the following resolutions: 144p, 240p, 360p, 480p, 720p,
1080p, 1440p, 2160p
Check the video for available resolutions.

Conclusion
In this tutorial, you learned how you can use PyTube and FFmpeg libraries to
download videos from a YouTube playlist in high resolutions such as 1080p, 1440p,
and even 2160p.

I hope you found the tutorial helpful. If so, don’t forget to star the GitHub gist and
share this tutorial with others.

The code has been tested with Pytube 12.1.3. It may not work properly at a later point in
time.

More content at PlainEnglish.io.

Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and
Discord.

Python Automation Pytube Programming Coding

https://python.plainenglish.io/how-to-download-youtube-playlist-using-python-4e832989e017 9/17
1/16/24, 10:18 PM How to Download YouTube Playlist Using Python | by Ashutosh Krishna | Python in Plain English

Follow

Written by Ashutosh Krishna


249 Followers · Writer for Python in Plain English

Application Developer at Thoughtworks

More from Ashutosh Krishna and Python in Plain English

Ashutosh Krishna in Analytics Vidhya

Why pipenv over venv for Python projects?


This post explains how working with virtual environments have now become easier with the use
of pipenv.

4 min read · Sep 21, 2020

141 1

https://python.plainenglish.io/how-to-download-youtube-playlist-using-python-4e832989e017 10/17
1/16/24, 10:18 PM How to Download YouTube Playlist Using Python | by Ashutosh Krishna | Python in Plain English

Artem Shelamanov in Python in Plain English

Top-5 Python Frontend Libraries for Data Science


There are many frontend libraries in Python, each with it’s unique advantages and
disadvantages. Which one should you choose?

7 min read · Dec 24, 2023

1K 12

Jesús Lagares in Python in Plain English

Why Are There So Many Programmers Who Cannot Find Jobs?


https://python.plainenglish.io/how-to-download-youtube-playlist-using-python-4e832989e017 11/17
💸
1/16/24, 10:18 PM How to Download YouTube Playlist Using Python | by Ashutosh Krishna | Python in Plain English

Why code sniffing is no longer worth obtaining $100.000/y salaries.

· 4 min read · Dec 6, 2023

1.6K 46

Ashutosh Krishna

The #1 Nodejs ecommerce backend: Medusa


Learn about Medusa, the #1 Node.js ecommerce backend.

7 min read · Jan 11, 2023

See all from Ashutosh Krishna

See all from Python in Plain English

https://python.plainenglish.io/how-to-download-youtube-playlist-using-python-4e832989e017 12/17
1/16/24, 10:18 PM How to Download YouTube Playlist Using Python | by Ashutosh Krishna | Python in Plain English

Recommended from Medium

Bosko Savic

Python & Fifth Grade Math Adventures 📘🐍


It’s the weekend, and my daughter is practicing mathematics for a test
which area she’s focusing on, she replied that…
📚 . When I asked her

3 min read · Jan 7

56

https://python.plainenglish.io/how-to-download-youtube-playlist-using-python-4e832989e017 13/17
1/16/24, 10:18 PM How to Download YouTube Playlist Using Python | by Ashutosh Krishna | Python in Plain English

Gopeshkhandelwal

Automating Instagram Posts with Python using instagrapi


In today’s digital age, social media platforms play a significant role in our lives. Instagram,
being one of the most popular platforms…

3 min read · Aug 11, 2023

Lists

Coding & Development


11 stories · 382 saves

General Coding Knowledge


20 stories · 796 saves

Stories to Help You Grow as a Software Developer


19 stories · 714 saves

Predictive Modeling w/ Python


20 stories · 789 saves

https://python.plainenglish.io/how-to-download-youtube-playlist-using-python-4e832989e017 14/17
1/16/24, 10:18 PM How to Download YouTube Playlist Using Python | by Ashutosh Krishna | Python in Plain English

Ritik khandelwal

Automating Video Editing with Python: Efficiency and Creativity


Combined
In this blog we will use python to automate our video editing process.The repeating stuff like
cutting and then merging the video can be…

4 min read · Jul 30, 2023

Tóth Máté in Django Unleashed

https://python.plainenglish.io/how-to-download-youtube-playlist-using-python-4e832989e017 15/17
1/16/24, 10:18 PM How to Download YouTube Playlist Using Python | by Ashutosh Krishna | Python in Plain English

Custom User Model In Django


A detailed explanation of custom user model and authentication in Django

16 min read · Jan 9

141

Avnish Kumar Thakur

Automate Your Instagram Likes with Python and Selenium


In this tutorial, I’ll show you how to automate your Instagram likes using Python and Selenium.
We will write a simple script that searches…

3 min read · Aug 2, 2023

https://python.plainenglish.io/how-to-download-youtube-playlist-using-python-4e832989e017 16/17
1/16/24, 10:18 PM How to Download YouTube Playlist Using Python | by Ashutosh Krishna | Python in Plain English

SarahDev

Automate WhatsApp Messages With Python using Pywhatkit module


Automating WhatsApp messages using Python and the Pywhatkit module is a fun and useful
project. Pywhatkit is a Python library that allows…

· 2 min read · Aug 4, 2023

242 1

See more recommendations

https://python.plainenglish.io/how-to-download-youtube-playlist-using-python-4e832989e017 17/17

You might also like