如何修复YouTube API调用出现的“The request specifies an invalid page token”错误
问题原因
- 直接通过键名读取
nextPageToken:YouTube API仅在存在下一页数据时才会返回该字段,直接用response["nextPageToken"]可能触发KeyError,极端情况下会取到异常值传入下一次请求 - 未做异常重试:
invalidPageToken报错多为API侧偶发故障、请求频率过高触发临时限制导致,属于偶发错误无固定复现位置,重试即可解决
修复方案
给请求增加重试逻辑,同时改用dict.get()方法读取分页token,调整后代码如下:
from googleapiclient.errors import HttpError import time # 传入播放列表ID,返回该列表下所有视频的ID def get_videos_in_playlist(self,playlist_id): list_of_videos = list() next_page = None max_retry = 3 # 单次请求最大重试次数 while True: # 请求重试逻辑 for retry_cnt in range(max_retry): try: request=self.api_resource.playlistItems().list( part="id,snippet,contentDetails,status", playlistId=playlist_id, maxResults=50, pageToken=next_page ) response=request.execute() break except HttpError as e: # 无效分页token、服务端错误类异常等待后重试 if e.status_code in (400, 500, 502, 503) and retry_cnt < max_retry - 1: time.sleep(1) continue # 超过重试次数抛出异常 raise # 处理当前页视频 for video in response["items"]: list_of_videos.append(video["contentDetails"]["videoId"]) # 用get方法读取分页token,不存在时默认返回None next_page = response.get("nextPageToken") if not next_page: return list_of_videos
内容的提问来源于stack exchange,提问作者NMEW
相关产品推荐
相关产品推荐

