使用Python调用Google Places API分页获取餐厅数据时请求无效求助
解决Google Places API分页请求返回INVALID REQUEST的问题
我之前调用Google Places API分页时也碰到过一模一样的问题——第一页正常,用next_page_token请求第二页就报INVALID REQUEST,但复制URL手动访问却没问题。折腾了一阵后,发现主要是两个容易忽略的细节导致的,给你分享下解决方案:
1. 必须等待1-2秒再使用next_page_token
Google Places API的next_page_token不是生成后立即可用的,服务器需要一点时间同步这个token的状态。如果刚拿到token就立刻发起第二页请求,服务器还没完成同步,就会返回INVALID REQUEST;而你手动点击URL时,已经过了几秒,token刚好生效,所以能正常返回结果。
解决方法很简单:在发起分页请求前加个延迟,比如time.sleep(2),给服务器足够的同步时间。
2. 分页请求不要重复传递原始查询参数
很多人会犯这个错:第一页请求时传了location、radius、type这些参数,分页时也把这些参数和pagetoken一起传。但实际上,next_page_token已经关联了你的原始查询条件,重复传递这些参数会导致请求冲突,触发INVALID REQUEST。
正确的分页请求只需要传递两个参数:key和pagetoken。
修正后的示例代码
import requests import time # 替换成你的API密钥 API_KEY = "your_api_key_here" target_location = "37.7749,-122.4194" # 示例坐标:旧金山 search_radius = 1000 # 单位:米 place_type = "restaurant" # 第一页请求 first_page_params = { "key": API_KEY, "location": target_location, "radius": search_radius, "type": place_type } response = requests.get( "https://maps.googleapis.com/maps/api/place/nearbysearch/json", params=first_page_params ) result_data = response.json() # 处理第一页结果(这里根据你的需求自行编写逻辑) print("第一页结果数量:", len(result_data.get("results", []))) # 处理分页逻辑 while "next_page_token" in result_data: # 关键:等待2秒再发起分页请求 time.sleep(2) # 分页请求只传key和pagetoken,不要加其他原始参数 paginate_params = { "key": API_KEY, "pagetoken": result_data["next_page_token"] } response = requests.get( "https://maps.googleapis.com/maps/api/place/nearbysearch/json", params=paginate_params ) result_data = response.json() # 处理当前分页的结果 print(f"当前页结果数量:", len(result_data.get("results", [])))
额外排查点
如果上面的方法还没解决问题,可以检查这两点:
- 确认
next_page_token的提取是否正确:从第一页响应的JSON里取result_data["next_page_token"],不要拼错字段名(Google返回的是蛇形命名,不是驼峰)。 - 用
requests的params字典传递参数,不要手动拼接URL:requests会自动处理URL编码和参数格式,避免手动拼接时出现的编码错误。
内容的提问来源于stack exchange,提问作者user9860931
相关产品推荐
相关产品推荐

