1
votes

I'm trying to have a list of all playlists from a specific channel in youtube API ... in python I'd like to have a list of playlist_id in a array

all_playlist_item = []

if I launch https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UC1udnO-W6gpR9qzleJ5SDKw&key=xxxxxx

here's the response from this request

 {
  "kind": "youtube#playlistListResponse",
  "etag": "PMwo-9BIp7p_L2ynH9sFOGIOido",
  "nextPageToken": "CAUQAA",
  "pageInfo": {
    "totalResults": 17,
    "resultsPerPage": 5
  },
  "items": [
    {
      "kind": "youtube#playlist",
      "etag": "-V67IpyB9a1JGDGJ4pVQnEoMRy4",
      "id": "PLWi7PxnyAMeN1tb-ldDzJcnJy2yd5wYrO",
      "snippet": {

...

I thing i have to used nextPageToken, but I don't know how to code this function for playlist items

Here's my code (extract in excel all videos just from a specific playlist)

channel_name="UC1udnO-W6gpR9qzleJ5SDKw"
playlist_name="PLWi7PxnyAMeOJmVLv8Z_N3edNyipsnHbo"



api_key = "xxxxxx"

from apiclient.discovery import build
import pandas as pd

youtube = build('youtube', 'v3', developerKey=api_key)



def get_channel_videos(channel_id):

# get Uploads playlist id
res = youtube.channels().list(id=channel_id, 
                              part='contentDetails').execute()
playlist_id = res['items'][0]['contentDetails']['relatedPlaylists']['uploads']

videos = []
next_page_token = None

while 1:
    res = youtube.playlistItems().list(playlistId=playlist_name, 
                                       part='snippet', 
                                       maxResults=50,
                                       pageToken=next_page_token).execute()
    videos += res['items']
    next_page_token = res.get('nextPageToken')

    if next_page_token is None:
        break

return videos

videos = get_channel_videos(channel_name)


def get_videos_stats(video_ids):
stats = []
for i in range(0, len(video_ids), 50):
    res = youtube.videos().list(id=','.join(video_ids[i:i+50]),
                               part='statistics').execute()
    stats += res['items']

return stats

video_ids = list(map(lambda x:x['snippet']['resourceId']['videoId'], videos))

stats = get_videos_stats(video_ids)


d = []
if len(stats)!=len(videos):
    i=1
    j=0
else:
    i=0
    j=0
len_video = len(videos)
len_stats = len(stats)
for video in videos:
    if i >= len_video:
        break
    Url_video='https://www.youtube.com/watch?v='+videos[i]['snippet']['resourceId']['videoId']+'&list='+playlist_name
    d.append((videos[i]['snippet']['title'], 
              videos[i]['snippet']['resourceId']['videoId'], 
              Url_video, 
              stats[j]['statistics']['viewCount'],
              stats[j]['statistics']['likeCount'],
              stats[j]['statistics']['dislikeCount']
              ))

    i+=1
    j+=1


df=pd.DataFrame(d, columns=('Titre_video', 'ID_video', 'Url_video','vues','like','dislike'))
df['vues'] = df['vues'].astype(int)
df['like'] = df['like'].astype(int)
df['dislike'] = df['dislike'].astype(int)
df.index+=1

df.to_excel("youtube-playlist.xlsx")
1

1 Answers

2
votes

From the pagination doc, you can use :

  • youtube.playlistItems().list_next(request, response) for iterating playlist item response
  • youtube.playlists().list_next(request, response) for iterating channel response

Get all videos from Playlist

import googleapiclient.discovery

playlist_id = "PLWi7PxnyAMeOJmVLv8Z_N3edNyipsnHbo"

youtube = googleapiclient.discovery.build("youtube", "v3", developerKey = "YOUR_API_KEY")

request = youtube.playlistItems().list(
    part = "snippet",
    playlistId = playlist_id,
    maxResults = 50
)
response = request.execute()

playlist_items = []
while request is not None:
    response = request.execute()
    playlist_items += response["items"]
    request = youtube.playlistItems().list_next(request, response)

print(f"total: {len(playlist_items)}")
print(playlist_items)

Get all playlists from channel

import googleapiclient.discovery

channel_id = "UC1udnO-W6gpR9qzleJ5SDKw"

youtube = googleapiclient.discovery.build("youtube", "v3", developerKey = "YOUR_API_KEY")

request = youtube.playlists().list(
    part = "snippet",
    channelId = channel_id,
    maxResults = 50
)
response = request.execute()

playlists = []
while request is not None:
    response = request.execute()
    playlists += response["items"]
    request = youtube.playlists().list_next(request, response)

print(f"total: {len(playlists)}")
print(playlists)