如何从 YouTube 播放列表中获取视频 ID?

How to get video ids from an YouTube playlist?

"googleapis": "^16.1.0"

我有一个播放列表,其中有两个视频。如何获取视频 ID?

我试过这个:

// Node.js
const google = require('googleapis');
const youtube = google.youtube('v3');
const secrets = require('./secrets.json');

const results = youtube.playlists.list({
  auth: secrets.web.api_key,
  part: 'id',
  id: 'PLvxLmGsmqdZc-GYVeLhS0N_6jfrzEleQm'
});

console.log(results);

代码执行后,我收到:https://gist.github.com/SergeyBondarenko/ea6a2aad546ded32e4a9b3cf53228fef

而且只有播放列表id:

// Node.js
> results.responseContent.body.items
[ { kind: 'youtube#playlist',
    etag: '"gMxXHe-zinKdE9lTnzKu8vjcmDI/cYPhPXIoWu4acW3Qux1D5WZ3WwE"',
    id: 'PLvxLmGsmqdZc-GYVeLhS0N_6jfrzEleQm' } ]

我在 results 对象中没有 items 属性:

// Node.js
> request.i
request.isPrototypeOf  
request.init   

据我了解 items 属性 必须包含结果,如下例所示:

 // Python
 results = youtube.playlists().list(
    part="snippet,localizations",
    id=playlist_id
  ).execute()

  playlist = results["items"][0]

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

我使用了错误的方法来检索播放列表视频 ID。使用方法是playlistItems:

// Node.js
const { google } = require('googleapis');
const youtube = google.youtube('v3');
const secrets = require('./secrets.json');

youtube.playlistItems.list({
  key: secrets.web.api_key,
  part: 'id,snippet',
  playlistId: 'PLvxLmGsmqdZc-GYVeLhS0N_6jfrzEleQm',
  maxResult: 10,
}, (err, results) => {
  console.log(err ? err.message : results.items[0].snippet);
});

结果:

{ publishedAt: '2017-01-21T13:16:09.000Z',
  channelId: 'UCSD9RekiljT4DzK_6VvYY6A',
  title: 'Monster (feat. Jay-Z, Nicki Minaj, Rick Ross, Bon Iver)',
  description: 'Oficial',
  thumbnails:
   { default:
      { url: 'https://i.ytimg.com/vi/EOpQdJ5F5TI/default.jpg',
        width: 120,
        height: 90 },
     medium:
      { url: 'https://i.ytimg.com/vi/EOpQdJ5F5TI/mqdefault.jpg',
        width: 320,
        height: 180 },
     high:
      { url: 'https://i.ytimg.com/vi/EOpQdJ5F5TI/hqdefault.jpg',
        width: 480,
        height: 360 },
     standard:
      { url: 'https://i.ytimg.com/vi/EOpQdJ5F5TI/sddefault.jpg',
        width: 640,
        height: 480 } },
  channelTitle: 'Sergey Bondarenko',
  playlistId: 'PLvxLmGsmqdZc-GYVeLhS0N_6jfrzEleQm',
  position: 0,
  resourceId: { kind: 'youtube#video', videoId: 'EOpQdJ5F5TI' } }

使用 Axios,您可以执行类似的操作:

import axios from "axios";
const KEY = "";

const getPlayListItems = async playlistID => {
    const result = await axios.get(`https://www.googleapis.com/youtube/v3/playlistItems`, {
      params: {
        part: 'id,snippet',
        maxResults: 10,
        playlistId: playlistID
        key: KEY
      }
    });
    return result.data;
  };

  getPlayListItems("PlaylistID").then(data => {
    data.items.forEach(element => {
        console.log(element.snippet.resourceId.videoId)
});

这将打印给定播放列表的所有 videoId,直到位置 10。