使用Google Places API按坐标搜酒店遇IndexError报错求助
问题排查与修复
错误原因
参数格式不符合API要求
Google Places Nearby Search API的location参数需要是逗号分隔的纬度+经度字符串(例如"-18.3693,26.5019"),你直接传入了整个target_locations二维列表,API无法解析该参数,返回的results为空数组,因此调用results[0]时触发IndexError。循环变量名不匹配
循环语句写的是for loc in locations:,但你定义的坐标列表变量是target_locations,变量名不一致导致循环没有遍历目标坐标。未动态更新请求参数
即使循环变量正确,你也没有在每次循环时更新my_params中的location值,所有请求都使用了错误的初始参数。未处理空结果场景
部分坐标在指定半径内可能确实没有酒店,即使参数正确,results也会是空数组,直接取索引0必然报错。
修复后的代码
import requests import time target_locations = [[-18.3693, 26.5019], [51.3813, 1.3862], [40.8106, 111.6522], [-17.65, -62.75], [49.6383, -1.5664], [38.4661, 68.8053], [43.9098, 67.2495], [45.55, 2.3167], [55.756, -4.8556]] target_search = "Hotel" radius = 5000 base_url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json" g_key = "你的API密钥" # 替换为实际密钥 # 遍历每个坐标搜索附近首个酒店 for loc in target_locations: # 将坐标转换为API要求的字符串格式 location_param = f"{loc[0]},{loc[1]}" # 每次循环构建新的请求参数 request_params = { "location": location_param, "keyword": target_search, "radius": radius, "key": g_key } response = requests.get(base_url, params=request_params).json() # 检查是否有搜索结果 if "results" in response and len(response["results"]) > 0: first_hotel = response["results"][0]["name"] print(f"坐标{loc}附近首个酒店:{first_hotel}") else: print(f"坐标{loc}在{radius}米范围内未找到酒店") time.sleep(1)
核心修正说明
- 把每个坐标转为
纬度,经度格式的字符串,严格匹配API参数要求。 - 修正循环变量为
target_locations,确保遍历所有目标坐标。 - 每次循环重新生成请求参数,动态替换当前坐标。
- 增加结果非空判断,避免索引越界错误。
内容的提问来源于stack exchange,提问作者Itsnhantransitive
相关产品推荐
相关产品推荐

