You need to enable JavaScript to run this app. Python调用Gmaps Places API使用page_token仍仅返回20条地点结果
优惠活动
大模型
产品
解决方案
定价
更多

Python调用Gmaps Places API使用page_token仍仅返回20条地点结果

问题原因定位
  • 结果集未合并:当前的详情遍历逻辑只绑定了首次搜索的places_result对象,通过page_token拉取到的后续分页结果完全没有被纳入处理流程,相当于无效请求。
  • 分页等待逻辑不可靠:page_token生成后存在服务端生效延迟,固定等待5秒并非100%覆盖生效周期,未生效的token会导致请求返回空结果或报错,无法正常拉取后续数据。
  • 接口返回上限限制:邻近搜索单检索条件下最多返回60条结果(分3页,每页最多20条),如果目标300米范围内符合条件的咖啡馆本身不足20条,接口不会返回next_page_token,自然无法获取更多数据。
正确分页实现代码
import time
import pprint

# 存储所有获取到的地点ID,自动去重
all_place_ids = set()

# 首次发起邻近搜索
places_result = gmaps.places_nearby(
    location='-6.880270,107.60794',
    radius=300,
    type='cafe'
)
# 收录第一页的地点ID
all_place_ids.update(p['place_id'] for p in places_result.get('results', []))

# 循环拉取所有分页
while 'next_page_token' in places_result:
    # 带重试的分页请求,解决token生效延迟问题
    for retry in range(3):
        time.sleep(3)
        try:
            places_result = gmaps.places_nearby(page_token=places_result['next_page_token'])
            all_place_ids.update(p['place_id'] for p in places_result.get('results', []))
            break
        except Exception:
            # 请求失败时延长等待时间重试
            time.sleep(2)

# 批量获取所有地点的详情
my_fields = ['name','formatted_address','business_status','rating','user_ratings_total','formatted_phone_number']
for place_id in all_place_ids:
    place_detail = gmaps.place(place_id=place_id, fields=my_fields)
    pprint.pprint(place_detail['result'])
额外注意事项
  • 原始代码的location参数前多了一个空格,虽部分接口会做容错处理,但建议移除避免参数识别异常。
  • 如果运行修正后的代码后,总获取到的地点数仍小于20,说明目标范围内符合条件的咖啡馆本身数量不足,属于正常业务结果,而非代码逻辑问题。
  • 邻近搜索接口的单检索结果上限为60条,即使目标区域内符合条件的地点超过60个,也不会返回更多分页结果,这是接口的硬限制。

内容的提问来源于stack exchange,提问作者Nizariansyah Agung

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.30 03:06:04