Retrieve all videos from youtube playlist using yo

2019-01-04 06:42发布

Im retrieving videos of a playlist using youtube v3 API and getting 50 items without any problem with this link:-

https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=PLB03EA9545DD188C3&key=MY_API_KEY

But the video count is 100 and im only getting 50. How can i get the next 50 items? I tried start-index but it doesnot work for v3 API. Any help is appreciated.

6条回答
叛逆
2楼-- · 2019-01-04 07:14

This is a small example made in python using the Python Youtube Client Lib This also borrows boilerplate setup from the youtube API examples

""" Pull All Youtube Videos from a Playlist """

from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser


DEVELOPER_KEY = "YOURKEY HERE"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

def fetch_all_youtube_videos(playlistId):
    """
    Fetches a playlist of videos from youtube
    We splice the results together in no particular order

    Parameters:
        parm1 - (string) playlistId
    Returns:
        playListItem Dict
    """
    youtube = build(YOUTUBE_API_SERVICE_NAME,
                    YOUTUBE_API_VERSION,
                    developerKey=DEVELOPER_KEY)
    res = youtube.playlistItems().list(
    part="snippet",
    playlistId=playlistId,
    maxResults="50"
    ).execute()

    nextPageToken = res.get('nextPageToken')
    while ('nextPageToken' in res):
        nextPage = youtube.playlistItems().list(
        part="snippet",
        playlistId=playlistId,
        maxResults="50",
        pageToken=nextPageToken
        ).execute()
        res['items'] = res['items'] + nextPage['items']

        if 'nextPageToken' not in nextPage:
            res.pop('nextPageToken', None)
        else:
            nextPageToken = nextPage['nextPageToken']

    return res

if __name__ == '__main__':
  # comedy central playlist, has 332 video
  # https://www.youtube.com/watch?v=tJDLdxYKh3k&list=PLD7nPL1U-R5rDpeH95XsK0qwJHLTS3tNT
  videos = fetch_all_youtube_videos("PLD7nPL1U-R5rDpeH95XsK0qwJHLTS3tNT")

videos will be a list of all your videos concatenated to the first list. It will keep fetching until it has all the videos because of pagination by 50. A similar approach can be taken in other languages.

In the list there will be all the individual video meta data and order

查看更多
干净又极端
3楼-- · 2019-01-04 07:15

YouTube Data API v3 results are paginated. So you need to get the next page of results for the others.

Basically in the response you have nextPageToken.

To get the remaining results, do the same exact call but setting pageToken into that token you received.

查看更多
Fickle 薄情
4楼-- · 2019-01-04 07:15

here is my recursive function, maybe can help somebody:

First at all I created a button for the first call:

<button id="aux" class="btn btn-danger">Click Me</button>    

Then in script section:

   $(document).ready(function () {

        function getVideos(t) {
            var url = "https://www.googleapis.com/youtube/v3/search?part=snippet&key=YourAPIKey&channelId=YourChannelID&maxResults=50";
            if (t != undefined) {
                url = url + "&pageToken=" + t
            }
            $.ajax({
                type: 'GET',
                url: url,
                dataType: 'json',
                success: function (html) {
                    console.log(html.items);
                    if (html.nextPageToken != undefined) {
                        getVideos(html.nextPageToken);
                    }
                }
            });
        };

        //initial call
        $("#aux").click(function () {
            getVideos();
        });
 });

Regards

查看更多
Juvenile、少年°
5楼-- · 2019-01-04 07:17

This javascript retrieves 115 clips (from PLTI6yRvQqlYq9KoU-NHu43uDmKON7Fsjv) and 91 clips (from PL32C69B40337EF920)
TEST THIS html file at:
http://pvhung20.url.ph/api3/retrieve-all-videos-stackoverflow.html

sum = 0;
sumN = 1;
var nextPageToken;

function getVids(PageToken){
    pid = $('#searchtext1').val();
    $.get(
        "https://www.googleapis.com/youtube/v3/playlistItems",{
        part : 'snippet', 
        maxResults : 50,
        playlistId : pid,
        pageToken : PageToken,
        key: 'YOUR API3 KEY'
        },
        function(data){
              myPlan(data);
        }        
    );  
 }

  function myPlan(data){
      total = data.pageInfo.totalResults;
      nextPageToken=data.nextPageToken;
      for(i=0;i<data.items.length;i++){
          document.getElementById('area1').value +=  
          sumN + '-' + data.items[i].snippet.title+'\n'+
          data.items[i].snippet.resourceId.videoId +'\n\n';
          sum++ ; sumN++;
          if(sum == (total-1) ){              
              sum = 0;  
              return;      
          }
      }  
      if(sum <(total-1)){
          getVids(nextPageToken);
      }    
 }
 
 function init(){
    $('#area1').val('');
 }
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
  
  <body onload="$('#area1').val('')">
    
  <input type="text"  value="PLTI6yRvQqlYq9KoU-NHu43uDmKON7Fsjv" 
  id="searchtext1" size="75">&nbsp;
  <button onclick="getVids()">Get Items</button>
  <br><br>
  IDs for test: <br>PLTI6yRvQqlYq9KoU-NHu43uDmKON7Fsjv<br>
  PL32C69B40337EF920
  <br><br>         
  <textarea id="area1" style="width:600px;height:500px">
  </textarea>

查看更多
疯言疯语
6楼-- · 2019-01-04 07:18

Ther are three tokes

  1. pageToken
  2. nextPageToken
  3. prevPageToken

and also you can set max page size using

maxResults=50 {allowed Values 1 to 50 }

if you are in page 1 you won't get prevPageToken

but you get nextPageToken

pass this token to next request's

pageToken = {nextPageToken get from last request}

this way you can navigate to next page Try it YourSelf

Edited

Ok, for other scenarios

If you are in any other page not is firs or last then there will be all these values

  1. pageToken = 'Some values'
  2. nextPageToken = 'Some values'
  3. prevPageToken = 'Some values'

@Manoj : you can find your answer below if you are in last page

  1. pageToken = 'Some values'
  2. nextPageToken = 'Some values'
  3. prevPageToken = null
查看更多
小情绪 Triste *
7楼-- · 2019-01-04 07:33

Another solution, using recursion:

$.fn.loadYoutubeResource = function(resource_request, resource_type, resource_id, resource_container, pageToken = null, callback = null){
    $.ajax({
            url: "https://www.googleapis.com/youtube/v3/" + resource_request,
            type: 'get',
            dataType: 'json',
            data: {
                    part : 'snippet', 
                    [resource_type]: resource_id,
                    maxResults : 50,
                    pageToken: pageToken,
                    key: '< API Key >', 
                  },
            success:    function(data) {
                                console.log("New resource " + resource_type + " loaded:");
                                console.log(data);                                          
                                for(var index = 0; index < data.items.length; index++){                                         
                                    var url = data.items[index]['snippet'].thumbnails.default.url;
                                    var ytb_id = data.items[index]['id'];   
                                    jQuery('#' + resource_container).append('<img class="tube_thumbs" src="' + url + '" id="' + ytb_id 
                                                                        + '" title="' + data.items[index]['snippet']['title'] + '" >');
                                    }
                                if ( data.nextPageToken == null)
                                    return callback();
                                $.fn.loadYoutubeResource(resource_request, resource_type, resource_id, resource_container, data.nextPageToken, callback);                   
                        }
            });     
        }        

And then call it as follows:

jQuery('body').append('<div id="ytb_container"></div>');

$.fn.loadYoutubeResource('playlistItems', 'playlistId', 'PLmwK57OwOvYVdedKc_vPPfbcsey_R0K8r', 'ytb_container', null, function(){ <callback code>});
查看更多
登录 后发表回答