JavaScript Youtube 数据 API - 分页

发布于 2025-01-09 18:07:37 字数 4805 浏览 0 评论 0原文

我对 JavaScript 和除一般基本程序之外的任何编程都很陌生。我认为构建一些东西是一种很好的学习方式。

目前我正在尝试使用 Youtube Data API。我想要做的是使用 OAuth 从任何已授权的 Youtube 帐户中提取订阅列表并将其保存在数组中。我按照 Google Developers 网站上的 JavaScript 快速入门进行操作。这很容易做到。我添加了将“title”中的键/值对存储到名为“allSubs”的数组中的代码。

<script>
  /**
   * Sample JavaScript code for youtube.subscriptions.list
   * See instructions for running APIs Explorer code samples locally:
   * https://developers.google.com/explorer-help/code-samples#javascript
   */

  allSubs = [];

  function authenticate() {
    return gapi.auth2.getAuthInstance()
        .signIn({scope: "https://www.googleapis.com/auth/youtube.readonly"})
        .then(function() { console.log("Sign-in successful"); },
              function(err) { console.error("Error signing in", err); });
  }
  function loadClient() {
    gapi.client.setApiKey("API_KEY");
    return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
        .then(function() { console.log("GAPI client loaded for API"); },
              function(err) { console.error("Error loading GAPI client for API", err); });
  }
  // Make sure the client is loaded and sign-in is complete before calling this method.
  function execute() {
    return gapi.client.youtube.subscriptions.list({
      "part": [
        "snippet,contentDetails"
      ],
      "maxResults": 50,
      "mine": true,
      "order": "alphabetical"
    })
        .then(function(response) {
                // Handle the results here (response.result has the parsed body).
                items = response.result.items;
                itemsLength = items.length;

                for  (i=0; i<itemsLength; i++){
                  x = response.result.items[i].snippet.title;
                  allSubs.push(x);
                }


                console.log(allSubs);
              },
              function(err) { console.error("Execute error", err); });
  }
  gapi.load("client:auth2", function() {
    gapi.auth2.init({client_id: "CLIENT_ID"});
  });
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>

我遇到的问题是分页。 “maxResults”的限制为 50。如果您订阅的频道超过 50 个,代码将不会选择它们。我必须使用“nextPageToken”根据需要循环多次才能获取完整列表。 我阅读了 Google 开发人员“实现:分页”页面,但我发现它没有帮助。然后我阅读了许多论坛(包括这个论坛)并观看了许多涵盖该主题的视频。我得到的最接近的是以下代码:

<script>
  /**
   * Sample JavaScript code for youtube.subscriptions.list
   * See instructions for running APIs Explorer code samples locally:
   * https://developers.google.com/explorer-help/code-samples#javascript
   */

  var allSubs = [];


  function authenticate() {
    return gapi.auth2.getAuthInstance()
        .signIn({scope: "https://www.googleapis.com/auth/youtube.readonly"})
        .then(function() { console.log("Sign-in successful"); },
              function(err) { console.error("Error signing in", err); });
  }
  function loadClient() {
    gapi.client.setApiKey("API_KEY");
    return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
        .then(function() { console.log("GAPI client loaded for API"); },
              function(err) { console.error("Error loading GAPI client for API", err); });
  }
  // Make sure the client is loaded and sign-in is complete before calling this method.
  function execute(pageToken, finished) {

      request = gapi.client.youtube.subscriptions.list({
        "part": [
          "snippet,contentDetails"
        ],
        "maxResults": 50,
        "mine": true,
        "order": "alphabetical",
        pageToken: pageToken
      });

      request.execute(function(response) {
        items = response.result.items;
        itemsLength = items.length;

        for  (i=0; i<itemsLength; i++){
          x = response.result.items[i].snippet.title;
          //y = response.result.items[i].snippet.resourceId.channelId;
          //z = [x,y];
          allSubs.push(x);
        }
        if (!response.nextPageToken)
            finished();
        else
            execute(response.nextPageToken, finished);
      });

      console.log(allSubs);
  }


  gapi.load("client:auth2", function() {
    gapi.auth2.init({client_id: "CLIENT_ID"});
  });


</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>

好消息是我现在有一个完整的列表。 但现在我有两个新问题。

  1. 除了给我想要的数组之外,我还有许多其他数组,它们是主数组的子集,间隔为 50 个。我想要一个数组。我显然以某种方式搞乱了循环。也许范围不正确,但我一直无法弄清楚;和

  2. 我收到一条错误消息“example.html:48 Uncaught TypeError: finish is not a function”。这是有道理的,因为我从未定义过“finished()”。但如果我不包含这个函数,代码似乎不起作用。我不知道为什么。

任何有关此特定问题或一般程序问题解决的帮助将不胜感激。可能有一个我忘记的简单解决方案。我又是一个初学者,可能在这里犯了一些愚蠢的错误。但我认为失败是一种很好的学习方式。

Im new to JavaScript and programming anything other than a basic programs in general. I figure that building something is a good way to learn.

At the moment I'm trying to use the Youtube Data API. What I want to do is use OAuth to pull a list of subscriptions from any Youtube account that's authorized and save it in an array. I followed the JavaScript Quickstart on the Google Developers website. That was easy enough to do. I added code that stores key/value pairs from 'title' into an array called 'allSubs'

<script>
  /**
   * Sample JavaScript code for youtube.subscriptions.list
   * See instructions for running APIs Explorer code samples locally:
   * https://developers.google.com/explorer-help/code-samples#javascript
   */

  allSubs = [];

  function authenticate() {
    return gapi.auth2.getAuthInstance()
        .signIn({scope: "https://www.googleapis.com/auth/youtube.readonly"})
        .then(function() { console.log("Sign-in successful"); },
              function(err) { console.error("Error signing in", err); });
  }
  function loadClient() {
    gapi.client.setApiKey("API_KEY");
    return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
        .then(function() { console.log("GAPI client loaded for API"); },
              function(err) { console.error("Error loading GAPI client for API", err); });
  }
  // Make sure the client is loaded and sign-in is complete before calling this method.
  function execute() {
    return gapi.client.youtube.subscriptions.list({
      "part": [
        "snippet,contentDetails"
      ],
      "maxResults": 50,
      "mine": true,
      "order": "alphabetical"
    })
        .then(function(response) {
                // Handle the results here (response.result has the parsed body).
                items = response.result.items;
                itemsLength = items.length;

                for  (i=0; i<itemsLength; i++){
                  x = response.result.items[i].snippet.title;
                  allSubs.push(x);
                }


                console.log(allSubs);
              },
              function(err) { console.error("Execute error", err); });
  }
  gapi.load("client:auth2", function() {
    gapi.auth2.init({client_id: "CLIENT_ID"});
  });
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>

The issue I ran into is pagination. The limit on 'maxResults' is 50. If you subscribe to more than 50 channels, the code won't pick them up. I have to use 'nextPageToken' to loop through as many times as needed to get the full list.
I read the Google Developer 'Implementation: Pagination' page but I didn't find it helpful. I then read many forums (including this one) and watched many videos that covered the topic. The closest I have gotten is the following code:

<script>
  /**
   * Sample JavaScript code for youtube.subscriptions.list
   * See instructions for running APIs Explorer code samples locally:
   * https://developers.google.com/explorer-help/code-samples#javascript
   */

  var allSubs = [];


  function authenticate() {
    return gapi.auth2.getAuthInstance()
        .signIn({scope: "https://www.googleapis.com/auth/youtube.readonly"})
        .then(function() { console.log("Sign-in successful"); },
              function(err) { console.error("Error signing in", err); });
  }
  function loadClient() {
    gapi.client.setApiKey("API_KEY");
    return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
        .then(function() { console.log("GAPI client loaded for API"); },
              function(err) { console.error("Error loading GAPI client for API", err); });
  }
  // Make sure the client is loaded and sign-in is complete before calling this method.
  function execute(pageToken, finished) {

      request = gapi.client.youtube.subscriptions.list({
        "part": [
          "snippet,contentDetails"
        ],
        "maxResults": 50,
        "mine": true,
        "order": "alphabetical",
        pageToken: pageToken
      });

      request.execute(function(response) {
        items = response.result.items;
        itemsLength = items.length;

        for  (i=0; i<itemsLength; i++){
          x = response.result.items[i].snippet.title;
          //y = response.result.items[i].snippet.resourceId.channelId;
          //z = [x,y];
          allSubs.push(x);
        }
        if (!response.nextPageToken)
            finished();
        else
            execute(response.nextPageToken, finished);
      });

      console.log(allSubs);
  }


  gapi.load("client:auth2", function() {
    gapi.auth2.init({client_id: "CLIENT_ID"});
  });


</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>

The good news is I have a complete list now.
But now I have two new problems.

  1. On top of giving me the array I wanted I also have a number of other arrays that are subsets of the main array in 50 intervals. I want a single array. I'm clearly messing up the loop somehow. Maybe the scope is incorrect but I haven't been able to figure it out; and

  2. I get an error that says 'example.html:48 Uncaught TypeError: finished is not a function'. Makes sense since I had never defined 'finished()'. But the code doesn't seem to work if I don't include this function. I have no idea why.

Any help would be greatly appreciated, either about this specific problem or about program problem solving generally. There's probably an easy solution that I'm oblivious to. Again Im a beginner and am probably making some dumb mistakes here. But I figure failing is a good way to learn.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文