Pobieranie wszystkich filmów z playlisty youtube za pomocą interfejsu API youtube v3

Pobieram filmy z playlisty za pomocą interfejsu API youtube v3 i otrzymuję 50 pozycji bez problemu z tym linkiem: -

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

Ale liczba filmów wynosi 100, a ja dostaję tylko 50. Jak mogę zdobyć następne 50 przedmiotów? Próbowałem start-index, ale nie działa to dla v3 API. Każda pomoc jest mile widziana.

Author: amrinder007, 2013-09-14

6 answers

Wyniki YouTube Data API v3 są paginowane. Więc musisz uzyskać następną stronę wyników dla innych.

W zasadzie w odpowiedzi masz nextPageToken .

Aby uzyskać Pozostałe wyniki, wykonaj dokładnie to samo wywołanie, ale ustaw pageToken w otrzymanym tokenie.

 39
Author: Ibrahim Ulukaya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-05 05:52:51

Ther są trzy tokes

  1. pageToken
  2. nextPageToken
  3. prevPageToken

A także możesz ustawić maksymalny rozmiar strony za pomocą

MaxResults=50 {dozwolone wartości od 1 do 50}

Jeśli jesteś na stronie 1 nie dostaniesz prevPageToken

Ale dostajesz nextPageToken

Przekaż ten token do następnego żądania

PageToken = {nextPageToken get from last request}

W ten sposób możesz przejść do następnej strony spróbuj Siebie

Edytowane

Ok, dla innych scenariuszy

Jeśli jesteś na innej stronie nie jest pierwsza lub ostatnia, wtedy będą wszystkie te wartości

  1. pageToken = 'niektóre wartości'
  2. nextPageToken = 'niektóre wartości'
  3. prevPageToken = 'niektóre wartości'

@ Manoj: odpowiedź znajdziesz poniżej jeśli jesteś na ostatniej stronie

  1. pageToken = 'niektóre wartości'
  2. nextPageToken = 'niektóre wartości'
  3. prevPageToken = null
 24
Author: Trikaldarshi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-14 16:26:49

Jest to mały przykład wykonany w Pythonie przy użyciu lib klienta Pythona Youtube To również zapożycza konfigurację boilerplate z przykładów interfejsu API youtube

""" 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")

Filmy będą listą wszystkich Twoich filmów połączonych z pierwszą listą. Będzie pobierał, dopóki nie będzie miał wszystkich filmów z powodu paginacji przez 50. Podobne podejście można zastosować w innych językach.

Na liście będą wszystkie metadane poszczególnych filmów i kolejność

 13
Author: stanzheng,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-18 13:47:58

Ten javascript pobiera 115 klipów (z PLTI6yRvQqlYq9KoU-Nhu43udmkon7fsjv) oraz 91 klipsów (z PL32C69B40337EF920)
Przetestuj ten plik html na:
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
Author: hung phan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-10 16:12:19

Inne rozwiązanie, używając rekurencji:

$.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);                   
                        }
            });     
        }        

A następnie nazwij to następująco:

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

$.fn.loadYoutubeResource('playlistItems', 'playlistId', 'PLmwK57OwOvYVdedKc_vPPfbcsey_R0K8r', 'ytb_container', null, function(){ <callback code>});
 0
Author: Samuel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-06 03:36:21

Oto moja funkcja rekurencyjna, może komuś pomoże:

Najpierw utworzyłem przycisk do pierwszego wywołania:

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

Następnie w sekcji skrypt:

   $(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();
        });
 });

Pozdrawiam

 0
Author: user3053204,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-03 11:17:25