Automatically Download YouTube Shorts - Once and for All with Simple Code!

YouTube shorts are all the rage these days, right? You're just one scroll away from watching a bunch of them, but if you want to download your own YouTube videos from an administrative level, it's a pain to manually click and download them one by one, right?

유튜브 쇼츠 자동 다운로드, 출처: Asoso's K-pop Vault
(Automatically download YouTube shorts, source: Asoso's K-pop Vault )

So today I've prepared a simple Python code to automatically download YouTube shorts from an acquaintance's channel! I'll explain it line by line to make it easy for beginners to follow along.

1. Prepare: Set up the YouTube API and yt-dlp

First, you'll need to set up the YouTube APIand yt-dlpis required. The YouTube API key is Google Cloud Consolewhich can be obtained from yt-dlpis a very useful tool for downloading videos from YouTube and other sites. To obtain a YouTube API key, you can use the YouTube List Extraction: How to Automate with APIs and Python Be sure to check out the post!

Installation commands

VS code In an IDE program terminal, such as yt-dlp To install, you can run the command below.

pip install yt-dlp
유튜브 쇼츠 자동 다운로드를 위한 패키지 설치 - VS code 터미널 화면
(Installing a package to automatically download YouTube shorts - VS code terminal screen)

2. Code Python to Automatically Download YouTube Shorts

유튜브 쇼츠 자동 다운로드
(Overview of the Python coding process for auto-downloading YouTube shorts)

Now that you have the basics ready, let's start coding in Python! The script (code) below will allow you to automatically download YouTube shorts. It saves the filename based on the title of each video, and works great for downloading age-restricted shorts.

from googleapiclient.discovery import build
import yt_dlp
import re

Enter your # API key
API_KEY = 'enter_API_key_here'

Set up the # YouTube API build
youtube = build('youtube', 'v3', developerKey=API_KEY)

Define functions to get the list of # shorts and their IDs
def get_shorts_titles_and_ids(channel_id, max_results=100):
    shorts_info = []
    next_page_token = None

    while len(shorts_info) < max_results:
        request = youtube.search().list(
            part='snippet',
            channelId=channel_id,
            maxResults=min(50, max_results - len(shorts_info)),
            type='video',
            videoDuration='short',
            pageToken=next_page_token
        )
        response = request.execute()

        for item in response['items']:
            title = item['snippet']['title']
            video_id = item['id']['videoId']
            shorts_info.append((title, video_id))

        next_page_token = response.get('nextPageToken')
        if not next_page_token:
            break

    return shorts_info[:max_results]

# video download function
def download_shorts(shorts_info):
    for idx, (title, video_id) in enumerate(shorts_info, 1):
        url = f"https://www.youtube.com/watch?v={video_id}"
        try:
            sanitized_title = re.sub(r'[\\/*?:"|]', "", title)
            filename = f"{idx}. {sanitized_title}.mp4"

            ydl_opts = {
                'format': 'best[ext=mp4]',
                'outtmpl': 'filename',
                'noplaylist': True,
            }

            with yt_dlp.YoutubeDL(ydl_opts) as ydl:
                print(f"Downloading: {filename}")
                ydl.download([url])
                print(f"Downloaded: {filename}")

        except Exception as e:
            print(f"Failed to download {title}: {e}")

Enter and execute the # channel ID
channel_id = 'enter_channel_id_here'
shorts_info = get_shorts_titles_and_ids(channel_id)
download_shorts(shorts_info)

3. line-by-line explanation of the code - All about Auto Download YouTube Shorts

Now let's go through each line of Python coding history line by line to see how it works!

  • API_KEYis where you enter your YouTube API key. Use the key you were issued in Google Cloud Console.
  • youtube = build('youtube', 'v3', developerKey=API_KEY)This is the step to connect to the YouTube API.
  • get_shorts_titles_and_ids function:
    • channel_id: Specifies the ID of the YouTube channel to download.
    • max_results: Specifies the maximum number of shorts to import. The default value is set to 100.
    • next_page_token: To get multiple pages of shorts nextPageTokento use the
    • video_id, titleExtract the ID and title of each short video and add it to the list.
  • download_shorts function:
    • yt_dlp.YoutubeDL(ydl_opts) as ydl: Download shorts videos with the YT-DLP library.
    • ydl_opts Settings: Download in mp4 format, outtmplto the filename.

When you run this code, the shorts are automatically downloaded from the YouTube channel you specify. The filename is saved based on the title of the short, so you can easily browse them as you wish.

4. FAQ - Frequently Asked Questions

Q1. What should I do if I can't download a video?

First, make sure that your API_KEY and channel_id are set correctly, and that yt-dlp is up to date, and if necessary, update it via pip install --upgrade yt-dlp in the terminal.

Q2. Can I download regular videos that are not YouTube shorts?

Yes, you can, if you remove the videoDuration='short' option from the get_shorts_titles_and_ids function, you can get and download all videos uploaded to the channel.

Q3. What if I only want to download in a specific resolution or quality?

You can specify the desired resolution by modifying the 'format' option in ydl_opts. For example, something like 'format': 'best[height<=720]' will only download at 720p or lower resolutions.

Q4. Can I save the video with a custom filename instead of a title?

Yes, you can change the filename variable to set it to any filename you want. For example, if you set it to "{idx}. CustomName.mp4" format, then each short will be saved with its own custom filename.

Q5. How do I download videos with age restrictions?

YT-DLP can bypass most age-restricted videos for download, but some videos may require additional authentication. If this is the case, see YT-DLP's documentation for detailed instructions on how to set this up.

Q6. What if I want to download more shorts at once?

By default, you can increase the number of shorts to fetch by adjusting the max_results parameter. However, we recommend downloading a maximum of 500 to account for the YouTube API's request limits.

Q7. Is there any way to speed up my downloads?

YT-DLP downloads videos at optimized speeds by default, but speeds may vary depending on your network environment. If you experience slow download speeds, try switching to a different network or checking your internet connection.

Q8. Can I download videos in a playlist with this code?

The current code is set to download only shorts from a specific channel. To download a playlist, you can specify playlistId instead of channelId and utilize yt-dlp's playlist option.

Q9. Is there a risk that my files will be duplicated or overwritten and downloaded?

The code adds a unique number for each video to the filename, so it's unlikely that the files will overlap. However, there may be instances where the titles are identical, so be sure to add a unique number, such as "{idx}. {sanitized_title}.mp4" or something like that, just make sure you add a unique number.

Q10. I get a 'Bad Request' error when I run the code. What is the reason?

A 'Bad Request' error can be caused by a problem with the API request, or a policy change on YouTube's end. In this case, double-check your API settings, or update yt-dlp and try again.

# Glossary

YouTube APIis a programming interface provided by YouTube that allows developers to integrate YouTube's features into their applications[1].

yt-dlp: A command-line program that allows you to download videos from various websites, including YouTube.

Google Cloud ConsoleA web-based interface provided by Google that allows developers to manage their Google Cloud projects and resources.

pipA tool for installing and managing Python packages.

IDEIE stands for Integrated Development Environment, which is software that provides the tools you need to write, debug, and run code in one program.

Channel ID: A string that uniquely identifies each channel on YouTube.

API keysA unique identifier that is required for authentication when an application uses the API.

FunctionA block of code that performs a specific task, making it reusable and helping to improve the structure of your program.

Exception handlingA programming technique for managing errors that may occur during program execution.

Resolution: A measure of the sharpness of a display or image, usually expressed as the number of pixels horizontally by vertical (e.g. 1920×1080).

Similar Posts