我正在尝试在YouTube数据API中获取nextPageToken
下面是我的代码,我想获取所有nextpageToken
。
在循环中,我想重新分配nextPageToken
def get_next_videos():
while True:
r = requests.get("https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=50&channelId="+CHANNELID+"&order=date&key="+DEVELOPER_KEY)
json_data = r.json()
nextPageToken = json_data.get("nextPageToken")
second_r = requests.get("https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=50&channelId="+CHANNELID+"&order=date&key="+DEVELOPER_KEY+"\
&pageToken="+nextPageToken)
json_data = second_r.json()
nextPageToken = json_data.get("nextPageToken")
third_r = requests.get("https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=50&channelId="+CHANNELID+"&order=date&key="+DEVELOPER_KEY+"&\
pageToken="+nextPageToken)
json_data = third_r.json()
nextPageToken = json_data.get("nextPageToken")
fourth_r = requests.get("https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=50&channelId="+CHANNELID+"&order=date&key="+DEVELOPER_KEY+"\
&pageToken="+nextPageToken)
json_data = third_r.json()
nextPageToken = json_data.get("nextPageToken")
最佳答案
假设在最后一页时不返回nextPageToken
,则可以执行以下操作:
# First request
r = requests.get("https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=50&channelId="+CHANNELID+"&order=date&key="+DEVELOPER_KEY)
json_data = r.json()
nextPageToken = json_data.get("nextPageToken")
# Retrieve all the rest of the pages
while nextPageToken:
r = requests.get("https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=50&channelId="+CHANNELID+"&order=date&key="+DEVELOPER_KEY+"&pageToken="+nextPageToken)
json_data = r.json()
nextPageToken = json_data.get("nextPageToken")
当然,在循环内部,您可能还希望以某种适当的数据结构(列表,字典等)收集要检索的数据。