Python使用Google Places API无法获取全部结果及分页报错求助
解决Google Places API无法获取全部结果的问题
嗨,我来帮你搞定这个问题~你遇到的两个核心问题:只能拿到20条结果、分页时触发INVALID_REQUEST错误,其实都是Google Places API的分页机制导致的,咱们一步步解决:
为什么会出现INVALID_REQUEST错误?
你添加的分页代码逻辑是对的,但Google Places API生成下一页的page token需要一点时间,如果在拿到token后立刻发起请求,这个token还没在Google服务器上生效,就会返回INVALID_REQUEST错误。
完整解决方案:循环分页+延迟请求
要获取所有可用结果(注意:Google Places Text Search最多返回60条结果,也就是3页),你需要:
- 每次拿到next_page_token后,等待2-3秒再请求下一页
- 用循环持续获取,直到没有下一页token为止
下面是修正后的完整代码:
from googleplaces import GooglePlaces, types, lang import time YOUR_API_KEY = 'xxxx' google_places = GooglePlaces(YOUR_API_KEY) # 初始化结果列表,用来存储所有页面的地点 all_places = [] # 第一页请求 query_result = google_places.text_search( query='Play Schools', location='Mumbai, India') # 添加第一页结果到列表 all_places.extend(query_result.places) # 处理分页 while query_result.has_next_page_token: # 等待3秒,确保token生效 time.sleep(3) # 请求下一页 query_result = google_places.text_search( pagetoken=query_result.next_page_token) # 添加当前页结果到列表 all_places.extend(query_result.places) # 输出所有结果 print(f"总共获取到 {len(all_places)} 条结果") for place in all_places: print(place.name) print(place.place_id) print('\n')
额外注意事项
- API配额与费用:Google Places API有调用次数限制和收费标准,获取大量结果可能会超出免费额度,记得在Google Cloud控制台监控你的使用情况
- 结果上限:Text Search接口最多返回60条结果,如果Google Maps上的结果更多,你可能需要尝试调整查询关键词,或者改用
nearby_search接口(需要指定半径等参数)来获取更多相关结果 - Token有效期:page token只能使用一次,且有效期很短(通常几分钟),所以要在拿到后尽快使用
内容的提问来源于stack exchange,提问作者Vizag
相关产品推荐
相关产品推荐

