How to get more results over 50 set by maxResults?

This source code working well. The maxResults cannot be set over the number 50.

API call to youtube.search.list failed with error: Invalid value '150'. Values must be within the range: [0, 50] (line 32, file "Code")

How to get more results?

function Search_YouTube_videos_ByChannel() {
  var results = YouTube.Search.list('id,snippet', {
    channelId:'UCZFUrFoqvqlN8seaAeEwjlw',
    maxResults: 50
  });
    var title = "";
    var id = "";
    var last_row = 0;
    var spread_active = SpreadsheetApp.getActiveSpreadsheet();
    var sheet1 = spread_active.getSheetByName("Sheet1");
    for (var i = 0; i < results.items.length; i++) {
        var item = results.items[i];
        title = item.snippet.title;
        id = item.id.videoId;
        last_row = sheet1.getLastRow() + 1;
        sheet1.getRange(last_row, 1).setValue(title);
        sheet1.getRange(last_row, 2).setValue(id);
        last_row++;
    }
}

Upvotes: 1

Views: 304

Answers (1)

Tanaike
Tanaike

Reputation: 201643

  • You want to retrieve all items from channelId.
  • You want to put title and videoId from the retrieved items to the column "A" and "B" of "Sheet1".

If my understanding is correct, how about this modification? Please think of this as just one of several answers.

Modification points:

  • When you want to retrieve the items more than 50, please use nextPageToken.
  • In your script, setValue() is used in the for loop. In this case, the process cost will become high. So in your case, you can use setValues().

When above points are reflected to your script, it becomes as follows.

Modified script:

When you use this, please enable YouTube Data API at Advanced Google Services.

function Search_YouTube_videos_ByChannel() {
  var items = [];
  var pageToken = "";
  do {
    var temp = YouTube.Search.list('id,snippet', {
      channelId:'UCZFUrFoqvqlN8seaAeEwjlw',
      maxResults: 50,
      pageToken: pageToken,
    });
    Array.prototype.push.apply(items, temp.items);
    pageToken = temp.nextPageToken || "";
  } while (pageToken);
  var spread_active = SpreadsheetApp.getActiveSpreadsheet();
  var sheet1 = spread_active.getSheetByName("Sheet1");
  var values = items.map(function(e) {return [e.snippet.title, e.id.videoId]});
  sheet1.getRange(sheet1.getLastRow() + 1, 1, values.length, values[0].length).setValues(values);
}

Note:

  • When this script is run, 410 items are retrieved.

References:

If I misunderstood your question and this was not the result you want, I apologize.

Upvotes: 2

Related Questions