调用Foursquare API时出现'groups'相关错误该如何解决?
Foursquare groups 报错排查方案
报错核心原因
你的代码直接硬取接口返回的["response"]['groups'][0]['items']字段,只要接口返回异常、无数据、权限校验失败时,返回结构中不存在groups字段就会触发报错,和你重置凭证没有必然关联,常见触发场景如下:
- 凭证配置依然无效:新注册的Foursquare应用默认发放Places API v3的密钥,无法兼容你调用的v2版本接口
VERSION参数格式错误:v2接口要求该参数为YYYYMMDD格式的日期值(例如20231001),格式错误会直接返回报错- 调用配额耗尽:免费层级的v2接口每日有调用次数上限,超出后接口会返回错误响应
- 查询坐标周边无符合条件的场地:500米半径内无匹配场地时,返回结构中
groups字段可能为空或不存在
修复方案
先给接口请求增加错误判断和异常捕获,先定位具体问题再针对性解决,修改后的代码参考如下:
import requests import pandas as pd def getNearbyVenues(names, latitudes, longitudes): radius=500 LIMIT=100 venues_list=[] for name, lat, lng in zip(names, latitudes, longitudes): print(f"正在处理:{name}") url = 'https://api.foursquare.com/v2/venues/explore?&client_id={}&client_secret={}&v={}&ll={},{}&radius={}&limit={}'.format( CLIENT_ID, CLIENT_SECRET, VERSION, lat, lng, radius, LIMIT) # 新增请求校验逻辑 try: resp = requests.get(url) resp.raise_for_status() # 捕获HTTP层面的报错 resp_json = resp.json() # 捕获业务层面的报错 if 'error' in resp_json: print(f"接口报错:{resp_json['error']['errorDetail']}") continue if 'response' not in resp_json or 'groups' not in resp_json['response'] or not resp_json['response']['groups']: print(f"{name} 周边无匹配场地,跳过") continue results = resp_json["response"]['groups'][0]['items'] except Exception as e: print(f"请求处理失败:{str(e)},接口返回内容:{resp.text if 'resp' in locals() else '无返回'}") continue venues_list.append([( name, lat, lng, v['venue']['name'], v['venue']['location']['lat'], v['venue']['location']['lng'], v['venue']['categories'][0]['name']) for v in results]) nearby_venues = pd.DataFrame([item for venue_list in venues_list for item in venue_list]) if not nearby_venues.empty: nearby_venues.columns = ['Neighborhood', 'Neighborhood Latitude', 'Neighborhood Longitude', 'Venue', 'Venue Latitude', 'Venue Longitude', 'Venue Category'] return(nearby_venues) illembe_venues = getNearbyVenues(names=df_illembe['Neighborhood'], latitudes=df_illembe['Latitude'], longitudes=df_illembe['Longitude'] )
运行修改后的代码,根据打印的报错信息对应处理即可:如果提示密钥无效就去Foursquare后台确认你使用的是v2接口的凭证;如果提示配额不足就次日再试或升级套餐;如果提示无匹配场地就放大radius参数的取值。
内容的提问来源于stack exchange,提问作者ash84
相关产品推荐
相关产品推荐

