YouTube List Extraction: How to Automate with APIs and Python

YouTubeto manage or analyze different content on YouTube, it is very useful to automatically extract YouTube lists. Using the YouTube Data API and Python, you can easily extract a list of shorts or general videos from a specific channel. In this article Step-by-step instructions on how to set up the API and write Python code to extract YouTube lists, including various use cases.Let's do it.

1. Preparing to extract your YouTube list

To extract a YouTube list YouTube Data APIis required. This API provides data on YouTube videos, channels, playlists, and more, which you can use to automatically collect the information you want.

1.1 Issuing a YouTube Data API key

First, Google Cloud Platform (GCP)to enable the YouTube Data API and obtain an API key. Follow the steps below to set this up.

  1. Google Cloud ConsoleLog in and create a new project (My First Project at the top of the site - NEW PROJECT - enter a project name and click CREATE)
  2. Click the top 3 lines menu on the left and go to APIs & Services > Library YouTube Data API v3and enable it (click ENABLE).
  3. In APIs and services > User credentials (Credentials), click the Generate and copy your API keyfor the API key. This API key is used in your Python code to connect with the YouTube Data API.

1.2 Verify your YouTube channel ID

You also need the ID of the channel whose list of videos you want to extract. You can find the channel ID in the channel URL. https://www.youtube.com/channel/UCxxxx The string that starts with UC in the URL in the form is your channel ID. You can find it in the address bar when you click Customize channel on your YouTube channel dashboard.

2. extract a list of YouTube shorts with Python

You can now extract a list of YouTube shorts in Python using the API key and channel ID you were issued. The API we'll be using is youtube.search()This API allows you to set search criteria and extract a list of shorts that match those criteria.

쇼츠 유튜브 리스트 추출 개요 그림

Python code example: Extracting a YouTube list of shorts


from googleapiclient.discovery import build

Enter your # API key
 api_key = 'your_api_key'

Build the # YouTube API service
youtube = build('youtube', 'v3', developerKey=API_KEY)

# Extract a list of shorts from a specific channel (including pagination)
def get_shorts_titles(channel_id, max_results=100):
    titles = []
    next_page_token = None

    while len(titles) < max_results:
        request = youtube.search().list(
            part='snippet',
            channelId=channel_id,
            maxResults=min(50, max_results - len(titles)), # 50 requests max, adjust request to fit remaining count
            type='video',
            videoDuration='short', # Fetch only short videos (shorts)
            pageToken=next_page_token
        )

        response = request.execute()

        Extract the title from the # result
        titles.extend([item['snippet']['title'] for item in response['items']])

        # Go to the next page
        next_page_token = response.get('nextPageToken')

        # Exit if there is no more next page
        if not next_page_token:
            break

    return titles[:max_results]

Enter your # channel ID
channel_id = 'YOUR_CHANNEL_ID'

Output a list of # shorts titles
shorts_titles = get_shorts_titles(channel_id, max_results=100)
for idx, title in enumerate(shorts_titles, 1):
    print(f"{idx}. {title}")

Code description:

  1. API connectionsConnect to the YouTube API service with the API key you were issued.
  2. Add a pagination: get_shorts_titles In a function nextPageTokento fetch results from multiple pages. Repeat until you have fetched up to 100 results.
  3. Change filter conditions: q='Shorts' condition so that the filtering is not too restrictive.
  4. Extract and print titles: Saves the titles of each video as a list and prints the specified number of titles.

When you run the code for the first time, the googleapiclient module is not installed and the error occurs. In a terminal window, type pip install google-api-python-client command to install the module.

3. Extract a YouTube list of videos with Python

YouTube now allows you to view shorts as well as regular List of videoscan also be easily extracted using Python. When extracting a list of videos, you can also use youtube.search() API, and with different search criteria, you can extract longer videos.

동영상 유튜브 리스트 추출 개요

Python code example: Extracting a list of YouTube videos

from googleapiclient.discovery import build
from datetime import timedelta

Enter your # API key
 api_key = 'your_api_key'

Build the # YouTube API service
youtube = build('youtube', 'v3', developerKey=API_KEY)

# Extract a list of general videos from a specific channel
def get_video_titles(channel_id, max_results=100):
    titles = []
    next_page_token = None

    while len(titles)  60: # Add only if longer than 60 seconds
                titles.append(item['snippet']['title'])

        # Go to next page
        next_page_token = search_response.get('nextPageToken')
        
        # Exit if there is no more next page
        if not next_page_token:
            break

    return titles[:max_results]

Function to convert # ISO 8601 duration to seconds
def parse_duration(duration):
    parsed_duration = timedelta()
    if 'PT' in duration:
        time_str = duration.replace('PT', '')
        hours = minutes = seconds = 0
        if 'H' in time_str:
            hours, time_str = time_str.split('H')
            parsed_duration += timedelta(hours=int(hours))
        if 'M' in time_str:
            minutes, time_str = time_str.split('M')
            parsed_duration += timedelta(minutes=int(minutes))
        if 'S' in time_str:
            seconds = time_str.replace('S', '')
            parsed_duration += timedelta(seconds=int(seconds))
    return parsed_duration.total_seconds()

Enter the # channel ID
channel_id = 'YOUR_CHANNEL_ID'

Output a list of # generic video titles
video_titles = get_video_titles(channel_id, max_results=100)
for idx, title in enumerate(video_titles, 1):
    print(f"{idx}. {title}")

Code description:

  1. Search requests: first search().listvia idto get the IDs of all videos in that channel.
  2. Check video length: videos().list method for each video in the contentDetailsand request durationto filter only videos longer than 60 seconds.
  3. Saving and printing video titles: Adds only videos with a length of 60 seconds or more to the list, and prints the title.

4. YouTube List Use Cases

This extracted list of YouTube shorts or videos can be used in a number of ways. Here are some of the most common ones

유튜브 리스트 활용사례 그림

4.1 Analyze content and identify trends

If you can automatically extract and analyze a list of YouTube videos, you can quickly identify trends in your content. For example, you can analyze the top videos from a particular channel to see what topics or formats are resonating well. You can save the extracted data in Excel, or combine it with additional analytics tools for deeper analysis.

4.2 Managing marketing campaigns

If you're using YouTube to promote your brand or product, you can extract a list of your competitors' videos and analyze which ones have the most views and what keywords they use in their titles. With this information, you can strategize your campaign and benchmark the elements of successful content.

4.3 Manage training content

Creators or businesses that need to manage large amounts of video content can benefit from an extracted video list to help manage their content. The API automatically collects data like titles, descriptions, and publication dates for all your videos and organizes them in a database or spreadsheet for easy management.

4.4 Create automated playlists

You can also use this method to automatically create playlists by categorizing videos uploaded to your channel. For example, you could extract only videos on a specific topic and create a playlist for that topic and update it automatically.

5. Organize

Extracting YouTube lists using the YouTube Data API and Python can be useful for content analytics, marketing strategy, training management, and more. You can easily extract not only shorts but also regular video lists, and the data you extract can help you plan and manage your content more efficiently. You can easily manage your YouTube data through API settings and Python code! If you're new to Python, start with the Installing VS CODE - Windows Take a look at the post to get started.

Similar Posts