Python调用Google Maps API获取数据生成空Excel文件的问题排查
排查Google Maps API获取清真餐厅数据生成空白Excel的问题
以下是导致空白文件的核心问题及修复方案:
半径参数单位错误:Places Nearby API的
radius单位是米,你设置的distance = 25仅搜索25米范围,这个区域内几乎不可能有餐厅。建议改为25000(对应25公里),覆盖合理的搜索范围。搜索参数冲突:同时使用
keyword和name参数会导致过滤逻辑过严。name='halal_restaurants'会强制匹配名称完全等于该字符串的地点,而真实餐厅不会用这个名称。直接删除name参数,仅保留keyword='halal restaurants'即可正确搜索清真餐厅。文件名格式错误:
'edmoton_rest.xlsx'.format(search_string)没有占位符,format完全无效,还存在拼写错误(edmoton应为edmonton)。建议改为带占位符的格式,同时处理空格:'{}.xlsx'.format(search_string.replace(' ', '_'))。缺少结果校验:未判断API是否返回有效结果,即使无数据也会生成空白Excel。添加结果检查逻辑,避免空文件生成,同时方便排查问题。
修正后的完整代码
import googlemaps import pandas as pd import time API_KEY = open('API_KEY.txt', 'r').read().strip() # 去除密钥中的换行符 map_client = googlemaps.Client(API_KEY) location = (53.53921005946531, -113.50032556307899) search_string = 'halal restaurants' radius = 25000 # 调整为25公里范围 edmonton_restaurants = [] # 发起初始搜索,移除冗余的name参数 response = map_client.places_nearby( location=location, keyword=search_string, radius=radius ) # 校验初始结果 if 'results' in response and response['results']: edmonton_restaurants.extend(response['results']) else: print("初始搜索无结果,请检查API密钥、配额或参数设置") next_page_token = response.get('next_page_token') # 分页获取后续结果 while next_page_token: time.sleep(3) # 必须等待3秒,避免API限制 response = map_client.places_nearby( location=location, keyword=search_string, radius=radius, page_token=next_page_token ) if 'results' in response and response['results']: edmonton_restaurants.extend(response['results']) next_page_token = response.get('next_page_token') # 有数据才生成Excel if edmonton_restaurants: df = pd.DataFrame(edmonton_restaurants) # 生成规范的文件名 output_file = '{}_edmonton_restaurants.xlsx'.format(search_string.replace(' ', '_')) df.to_excel(output_file, index=False) print(f"成功导出{len(edmonton_restaurants)}条清真餐厅数据到{output_file}") else: print("未找到符合条件的清真餐厅数据")
内容的提问来源于stack exchange,提问作者Rashad Bayram
相关产品推荐
相关产品推荐

