I would like to get YouTube data for a few anime titles. For each title I put in the query, I would like to retrieve 100 records.
I've used the pageToken in the parameters but I keep getting the error in the below image. I only get this error when I put maxResults : 50 in the for loop and while loop. When the maxResults parameter is less than 50 for both loops, its fine.
I've observed that the script throws an error when the total records that would be outputted for each anime title exceeds 50.
I don't understand why this error shows up because I thought the page tokens were to allow users to get more than 50 results, no?
Below is my code. Any help would be massively appreciated!
function youTubeData() {
var ss = SpreadsheetApp.openById(<your sheet ID>);
var activeSheet = ss.getSheetByName("YouTube Results");
activeSheet.getRange("A2:G").clear(); // clear old data
let executionTime = Utilities.formatDate(new Date(), "GMT+1", "yyyy/MM/dd HH:mm:ss");
var arrSearchItems = ["attack on titan", "mob psycho 100", "demon slayer", "vinland saga"];
for (let i = 0; i < arrSearchItems.length; i++) {
if(i>0) {break;} // for testing purposes only display Attack on Titan results
var query = arrSearchItems[i];
Logger.log((i+1) + ') ' + query.toUpperCase())
var videos = YouTube.Search.list('snippet', {
q : query,
type : 'video',
maxResults : 50,
order : "viewCount",
});
var allVideos = videos.items;
var iteration = 1;
while (videos.nextPageToken && iteration == 1 /* only return one extra page of youtube results - we only want 100 records for each anime */) {
Logger.log('iteration = ' + iteration)
var videos = YouTube.Search.list('snippet', {
q : query,
type : 'video',
maxResults : 50,
order : "viewCount",
pageToken : videos.nextPageToken,
});
iteration = iteration + 1;
allVideos = allVideos.concat(videos.items);
};
var modRes = allVideos.map( function (v) { return [query.toUpperCase(), 'https://youtu.be/' + v.id.videoId, v.snippet.title, v.snippet.publishedAt]; } );
var ids = modRes.map( function (res) { return res[1].split("/")[3]; }); // get ID of videos in modRes
var stats = YouTube.Videos.list("statistics", {'id' : ids}); // get the stats for each video
// build the video stats array
var vidsStats = stats.items.map ( function (res) { return [res.statistics.viewCount, res.statistics.likeCount, executionTime] } );
var rowStart = activeSheet.getLastRow() + 1 // row start for the next search query when outputting to GSheets
// output YouTube data to GSheets
activeSheet.getRange(rowStart, 1, modRes.length, modRes[0].length).setValues(modRes);
activeSheet.getRange(rowStart, 5, vidsStats.length, vidsStats[0].length).setValues(vidsStats);
}
}
