使用youtube v3 API从youtube播放列表中检索所有视频

时间:2013-09-14 18:12:57

标签: youtube youtube-api

我使用youtube v3 API检索播放列表的视频,并通过此链接获得50项没有任何问题: -

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

但是视频数量是100,我只得到50.如何获得接下来的50项? 我尝试了 start-index ,但它不适用于v3 API。 任何帮助表示赞赏。

9 个答案:

答案 0 :(得分:44)

YouTube Data API v3结果已分页。所以你需要为其他人获得下一页的结果。

回复中基本上有nextPageToken

要获得剩余的结果,请执行相同的确切调用,但将pageToken设置为您收到的令牌。

答案 1 :(得分:26)

Ther是三个tokes

  1. pageToken
  2. nextPageToken这个
  3. prevPageToken
  4. 您也可以使用

    设置最大页面大小
      

    maxResults = 50 {允许值1到50}

    如果您在第1页,则不会获得prevPageToken

    但是你得到了nextPageToken

    将此令牌传递给下一个请求的

      

    pageToken = {nextPageToken从上次请求中获取}

    这样您就可以导航到下一页Try it YourSelf

    被修改

    好的,对于其他场景

    如果您在任何其他页面中不是第一页或最后一页,那么将会有所有这些值

    1. pageToken ='某些值'
    2. nextPageToken ='某些值'
    3. prevPageToken ='某些值'
    4. @Manoj:您可以在下面找到答案 如果你在最后一页

      1. pageToken ='某些值'
      2. nextPageToken ='某些值'
      3. prevPageToken = null

答案 2 :(得分:15)

这是使用Python Youtube Client Lib在python中创建的一个小例子 这也借用了youtube API示例

中的样板设置
""" 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")

视频将是您连接到第一个列表的所有视频的列表。由于分页为50,因此它将持续获取所有视频。其他语言也可采用类似的方法。

在列表中将有所有单独的视频元数据和订单

答案 3 :(得分:9)

此javascript检索115个剪辑(来自PLTI6yRvQqlYq9KoU-NHu43uDmKON7Fsjv) 和91个夹子(来自PL32C69B40337EF920)
测试这个html文件:
http://pvhung20.url.ph/api3/retrieve-all-videos-stackoverflow.html

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

答案 4 :(得分:0)

使用递归的另一种解决方案:

 module.exports = {
  "env": {
    "browser": true,
    "node": true
  },
  "globals": {
    "SomeVar": true
  },
};

然后按如下方式调用它:

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

答案 5 :(得分:0)

这是我的递归函数,也许可以帮助某人:

首先,我为第一个通话创建了一个按钮:

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

然后在脚本部分:

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

致谢

答案 6 :(得分:0)

获取所有视频的最简单方法,

DEVELOPER_KEY = "REPLACE_ME" YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3"

youtube = build("youtube", "v3", developerKey=api_key)
def get_videos_from_playlist(youtube, items, playlistID):
    response = items.list(part="snippet", playlistId=playlistID)
    while response:
        playlistitems_list_response = response.execute()

        for playlist_item in playlistitems_list_response["items"]:
            # title = playlist_item["snippet"]["title"]
            video_id = playlist_item["snippet"]["resourceId"]["videoId"]
            yield video_id

        response = youtube.playlistItems().list_next(
        response, playlistitems_list_response)

传递播放列表ID,

items = youtube.playlistItems()
playlist = get_videos_from_playlist(youtube, items, 'PLoROMvodv4rOhcuXMZkNm7j3fVwBBY42z')

然后解析列表:

for videoID in playlist:
    print(videoID)

此外,您可以使用页面来抓取多个页面,例如:

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']

答案 7 :(得分:0)

另一种方式(无需知道请求格式并具有api键):只需在youtube播放列表html文件中使用json并使用JSON.parse方法
不幸的是,这种方法不能播放200多个视频。在json中,我看到了一些关键代码,也许是为了继续使用,但无法使用它们。
要获取html源代码,我们可以使用jquery $ .ajax方法。

<meta charset = utf-8>
<body>
<div id="help" style="width:90%">
1- Open youtube.com and search for playlist   (http://www.youtube.com/....&list=...)<br>
For example: click <a href="http://www.youtube.com/watch?v=sMyj9e2qOc0&list=PL33196EF7664597D5">paul mauriat playlist</a><br>
You will see in the adress bar: http://www.youtube.com/watch?v=sMyj9e2qOc0&list=PL33196EF7664597D5 <br>
Select all and copy this url.<br>
2- Open any online html source code  viewer. For example<br>
<a href="https://www.duplichecker.com/page-snooper.php">
https://www.duplichecker.com/page-snooper.php</a><br>
Paste the url, click "Enter", wait several seconds, scroll down, click   "Copy"<br>
3- Return to this page. Paste the code to the below input smal textarea, wait several seconds, click "GET VIDEO IDS".<br>
4- Click the button TEST JAVASCRIPT.
</div><br>
<textarea id = "input">
</textarea><br>
<button onclick="extract()">GET VIDEOS IDS</button><br>
Total:&nbsp;<span id='len'></span>
<br><button onclick="test()">TEST JAVASCRIPT</button><br>
COPY THIS TO CREATE A JAVASCRIPT FILE<br>
<textarea id="area2" style="width:90%;height:400px;font-size:14pt">
</textarea><br>

<script> 
function extract(){
str = document.getElementById('input').value;
aa = str.indexOf('{"responseContext');
bb = str.indexOf('{"related', aa);
jsn = str.substring(aa, bb + 24);
obje = JSON.parse(jsn);
alert('Click OK to continue');
make();
}
glStr = '';
function make(){
len = obje.contents.singleColumnWatchNextResults.playlist.playlist.contents.length;
ss = '';
for(i=0; i < len; i++){
try{
   ti = obje.contents.singleColumnWatchNextResults.playlist.playlist.contents[i].playlistPanelVideoRenderer.title.runs[0].text;
   ti1 = ti.replace(/"/g,'\\"');
   ide = obje.contents.singleColumnWatchNextResults.playlist.playlist.contents[i].playlistPanelVideoRenderer.navigationEndpoint.watchEndpoint.videoId;
    }catch(e){
                ide = obje.contents.singleColumnWatchNextResults.playlist.playlist.contents[i].playlistPanelVideoRenderer.videoId;
                ti1 = '[Deleted Video]';
}
    ss += '{vid:"' + ide + '",tit:"' + ti1 + '"}';
    if(i != (len - 1)){
        ss += ',\n';
    }
} 
glStr = 'obj = \n[' + ss + '\n];\n';
document.getElementById('area2').value = glStr;
document.getElementById('len').innerHTML = len + ' videos';
}
function test(){
var head = document.getElementsByTagName('head').item(0);
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.innerHTML = glStr;
head.appendChild(script);
 alert('obj.length = ' + obj.length);
 alert('obj[5].vid = ' + obj[5].vid + '\n obj[5].tit = ' +   obj[5].tit);
}
</script>
</body>

答案 8 :(得分:0)

我做了如下操作,但是我不知道这是优化的还是我没有得到预期的结果。

说明: 将从播放列表中检索所有视频,并动态推送到数组中。

服务中:

    getSnippets(token): any {
    console.log('API_TOKEN:',token);
    if(token){
      return this.http.get('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=PLV_aspERmuCKxUPxu8UwUd3I52VLje0ra&maxResults=100&key=[API_KEY]='+token).toPromise();
    }else{
      return this.http.get('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=PLV_aspERmuCKxUPxu8UwUd3I52VLje0ra&maxResults=100&key=[API_KEY]').toPromise();
    }
  }

显示数据:

      async getPlayList(){
    try{
      let pageToken;
      this.finalAr = [];
      // for(let t = 0; t <= 1; t++) {
        const list = await this.service.getSnippets(pageToken);
        pageToken          = list.nextPageToken;
        // let pageInfo       = list.pageInfo;
        let pageTot        = list.pageInfo.totalResults;
        let resultsPerPage = list.pageInfo.resultsPerPage;
        let loopCnt        = pageTot / resultsPerPage;
        let finalCnt       = Math.abs(Math.ceil(loopCnt)) - 1 ;
        if(pageToken != undefined || pageToken != null){
          let tempAr   = list.items;        
          for(let i = 0; i < tempAr.length; i++){
            this.finalAr.push({"vid_id"   : tempAr[i].snippet.resourceId.videoId,
                               "vid_title": tempAr[i].snippet.title,
                               "vid_desc" : tempAr[i].snippet.description,
                               "vid_icon" : 'https://i.ytimg.com/vi/'+tempAr[i].snippet.resourceId.videoId+'/sddefault.jpg'
                              })
          }
          console.log('finalAr_1:',this.finalAr);
        }
        for(let a = 1; a <= finalCnt; a++){
          const listF = await this.service.getSnippets(pageToken);
            pageToken = listF.nextPageToken;
            let tempAr   = listF.items;      
            for(let i = 0; i < tempAr.length; i++){
              this.finalAr.push({"vid_id"   : tempAr[i].snippet.resourceId.videoId,
                                 "vid_title": tempAr[i].snippet.title,
                                 "vid_desc" : tempAr[i].snippet.description,
                                 "vid_icon" : 'https://i.ytimg.com/vi/'+tempAr[i].snippet.resourceId.videoId+'/sddefault.jpg'
                                })
            }
            console.log('finalAr_2:',this.finalAr);
        }
    }catch (e){
      console.log('ER:',e);
    }

工作完成了。但是,如果有人知道这一点,我想从多个播放列表中检索所有视频。