首页 > 解决方案 > 如何使用 youtube api 修复“请求指定了无效的页面令牌”错误?

问题描述


    #given the playlist id this will return a list of the 
    #of all videos in the playlist
    #
    def get_videos_in_playlist(self,playlist_id):
        list_of_videos=list()              
        next_page=None
        ##python does not have a do while loop this is very similar to one
        while True:           
            request=self.api_resource.playlistItems().list(
                part="id,snippet,contentDetails,status",
                playlistId=playlist_id,
                maxResults=50,   
                pageToken=next_page
                )                
            response=request.execute()           
            next_page=response["nextPageToken"]            
            for video in response["items"]:
                list_of_videos.append(video["contentDetails"]["videoId"])
            if next_page==None:
                return list_of_videos

我正在尝试使用 youtube api 在 python 中编写一个方法,该方法将获取播放列表的 ID 并返回播放列表中所有视频的 ID。我希望它在返回列表之前浏览 50 个视频的每一页。但是,它最终会引发此错误:

Traceback (most recent call last):
  File "C:\Users\vdh24\source\repos\GraphAnalysis\youtube_info.py", line 86, in <module>
    youtube_info.test()
  File "C:\Users\vdh24\source\repos\GraphAnalysis\youtube_info.py", line 20, in test
    first_video_id=object.get_videos_in_playlist(id_of_playlist)[0]
  File "C:\Users\vdh24\source\repos\GraphAnalysis\youtube_info.py", line 50, in get_videos_in_playlist
    response=request.execute()
  File "C:\Users\vdh24\AppData\Roaming\Python\Python37\site-packages\googleapiclient\_helpers.py", line 131, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Users\vdh24\AppData\Roaming\Python\Python37\site-packages\googleapiclient\http.py", line 937, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://youtube.googleapis.com/youtube/v3/playlistItems?part=id%2Csnippet%2CcontentDetails%2Cstatus&playlistId=UUL5YbN5WLFD8dLIegT5QAbA&maxResults=50&pageToken=CN4CEAA&key=AIzaSyD1iei5Po9z1Qu7eSGZdzr357LMpLWnr4U&alt=json returned "The request specifies an invalid page token.". Details: "[{'message': 'The request specifies an invalid page token.', 'domain': 'youtube.parameter', 'reason': 'invalidPageToken', 'location': 'pageToken', 'locationType': 'parameter'}]">
The thread 'MainThread' (0x1) has exited with code 0 (0x0)

我尝试使用以下建议: 如何使用 nextPageToken 在频道中列出 50 多个 Youtube 视频? 但这似乎是我已经在做的事情。这个错误特别令人困惑,因为每次我运行代码时它似乎都出现在不同的页面上。提前致谢。

标签: pythongoogle-apiyoutube-api

解决方案


推荐阅读