使用Python调用Google API提取谷歌表格评论仅返回20条的问题咨询
解决Google表格评论提取不全的问题
你的问题出在Google Drive API v2的comments.list方法默认行为上:该方法默认仅返回最多20条评论(maxResults参数默认值为20),当评论总数超过这个值时,会返回nextPageToken用于分页获取剩余内容。要获取全部评论,需要修改代码实现分页迭代获取,同时可调整maxResults参数提高单次请求的返回数量(API允许的最大值为1000)。
修改后的retrieve_comments函数
def retrieve_comments(service, file_id): """Retrieve all comments for a file. Args: service: Drive API service instance. file_id: ID of the file to retrieve comments for. Returns: List of all comments. """ all_comments = [] page_token = None try: while True: # 设置maxResults为API允许的最大值1000,同时传入pageToken处理分页 comments = service.comments().list( fileId=file_id, maxResults=1000, pageToken=page_token ).execute() all_comments.extend(comments.get('items', [])) page_token = comments.get('nextPageToken') if not page_token: break return all_comments except errors.HttpError as error: print(f'An error occurred: {error}') return None
关键调整点
maxResults参数:手动设置为1000(API允许的最大值),减少请求次数pageToken参数:每次请求后检查返回结果中的nextPageToken,若存在则继续请求下一页,直到没有更多评论为止
内容的提问来源于stack exchange,提问作者PHV
相关产品推荐
相关产品推荐

