Youtube Api,如何使用 nextPageToken 解析所有视频? [英] Youtube Api, how to parse all vids with a nextPageToken?
问题描述
我正在使用 Node.JS 和请求"库 https://github.com/request/请求我阅读了文档,因为我只能从频道请求 50 个视频,作为来自 api 服务器的响应,有一个 nextPageToken 键,但我不明白如何使这个 nextPageToken 的请求链通过整个链条.
I'm using Node.JS, and the "request" library https://github.com/request/request I read the documentation, as much as I can request only 50 videos from the channel, in response from the api server, there is a nextPageToken key, but I do not understand how to make the chain of requests for this nextPageToken to go through the whole chain.
`https://www.googleapis.com/youtube/v3/search?key=${key}&channelId=${channelId}&part=snippet,id&order=date&maxResults=50`;
我草拟了这段代码
request({url:url}, function(err, response, body){
let data = JSON.parse(body);
for(let i = 0; i < Math.fround(data.pageInfo.totalResults / maxResults); i++){
let newUrl = url + '&pageToken=' + data.nextPageToken;
request({url: newUrl}, function(err, response, body){
newUrl = url + '&pageToken=' + JSON.parse(body).nextPageToken;
console.log(JSON.parse(body).nextPageToken);
})
}
})
在+450视频频道,没有想到最好的解决方案,取第一个请求的结果,除以请求视频的最大数量,我得到9-10,然后结果每个周期10遍,理论上每个请求都应该更新变量 newUrl
之后,再次访问服务器以获取新数据和新的 nextPageToken.
At channel +450 video, did not think of the best solution and take the result of the first request, and divide by the maximum number of requested video, I get 9-10, then it turns out 10 passes per cycle, and in theory each request should update the variable newUrl
And after, again access to the server for new data, and a new nextPageToken.
怎么样?
推荐答案
通常在处理 API 时使用 for 循环是不公平的,您可能希望更慢地单步执行您的请求.我下面的示例使用简单的递归,但您甚至可能希望在函数调用自身时添加超时.
Typically when dealing with API's its not fair to use a for loop, you may want to step through your requests slower. My below example uses simple recursion but you may want to even add a timeout when the function calls itself.
let url = 'formatted url'
let videos = [];
function worker = (token, url) {
//use the standard url if there is no token
if (!token) {
request({url:url}, function(err, response, body){
let data = JSON.parse(body);
//do something with data
//if there is a next page token run worker again.
if (data.nextPageToken) {
let token = data.nexPageToken;
return worker(token, url);
} else {
console.log('fin');
}
} else {
//if there is a token use a new url
let nurl = 'url + page token';
request({url: url}, function(err, response, body) {
let data = JSON.parse(body);
//do something with data
//if there is a token run the worker again
if (data.nextPageToken) {
let token = data.nextPageToken;
return worker(token, url);
} else {
console.log('fin');
}
})
}
}
worker(null, url);
这篇关于Youtube Api,如何使用 nextPageToken 解析所有视频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!