T.J. Kolberg
T.J. Kolberg

Reputation: 39

Getting YouTube Video URL with YouTube API in Python

I no longer have YouTube Premium, so I would like to write a Python script to simply look at the number of videos YouTubers I follow have uploaded, and when that number changes (a new video is posted), I would like the program to return the URL of the new video as a string. Then, with that string, I'd like to download the video, but I've already figured out that part.

Here's what I've got (in multiple files, but I'll write them in one file to make it more readable):

from os import system
from googleapiclient.discovery import build
from secret_stuff import api_key


def bash_command(user_input):
    _ = system(user_input)


def check_for_updates():
    youtube = build('youtube', 'v3', developerKey=api_key)

    request = youtube.channels().list(
        part='statistics',
        forUsername='RandomYouTuberNumberOneOrSomething'
    )

    response = request.execute()
    bash_command('rm test_file.py')
    bash_command(f"""echo 'yt_data = "{response}"' >> test_file.py""")

    from test_file import yt_data
    string_data = str(yt_data)
    video_count = int(string_data[-8:-4])
    print(video_count)


starting_video_count = check_for_updates()

while True:
    new_video_count = check_for_updates()
    if new_video_count == starting_video_count:
        print(f'Still {starting_video_count} videos.')
    else:
        print(f'There are now {new_video_count} videos!')

So from here, I am able to check for updates, and it seems to work pretty well. I've been going through the documentation (granted, this is my very first project where I've used an API), but I can't seem to find a way to extract the URL for the most recent (public) video posted by any given YouTuber. Any suggestions? Any help is greatly appreciated.

Upvotes: 2

Views: 3906

Answers (1)

TaeJun Moon
TaeJun Moon

Reputation: 41

Seems like everything is working fine, but you just need to extract the videoId of a specific channel.

On YouTube Data API, you can use search: list to find a video ID of a given channel.

https://developers.google.com/youtube/v3/docs/search/list

# Use Channel ID instead of username
channelID = 'YOUTUBE_CHANNEL_ID'

request = youtube.search().list(
    part='id',
    channelId=channelID,
    type='video',
    order='date',
    maxResults=50
)

response = request.execute()

Code above will return a dictionary response, and response['items'] will give you an array of video information dictionary objects. Something like this:

[{'kind': 'youtube#searchResult',
  'etag': '3UfKjZ-gZliijpKSD3vpug-ptaE',
  'id': {'kind': 'youtube#video', 'videoId': '4xA5JePvCJc'}},
 {'kind': 'youtube#searchResult',
  'etag': 'FERCCArCb0vmKunn-CAvomYuJMQ',
  'id': {'kind': 'youtube#video', 'videoId': 'ontX4zfVqK8'}}, ...]

All you need to do is extract the videoId part and put it on this URL: https://www.youtube.com/watch?v=VIDEO_ID

video_link_array = [f"https://www.youtube.com/watch?v={video['id']['videoId']}" \
                for video in response['items']]

You can store your video ids in a separate file and only retrieve the video id that is not present on that file.

Upvotes: 4

Related Questions