使用Python调用Google Maps API获取酒店电话失败求解决方案
解决Google Maps API无法获取酒店电话号码的问题
问题分析
你当前使用的Find Place from Text API存在局限性:它仅用于快速匹配地点,返回的字段有限,很多情况下不会包含formatted_phone_number这类详细信息。此外还可能存在以下问题:
- 搜索关键词过于模糊,导致匹配结果不准确
- API密钥未启用Places API权限、配额耗尽或未绑定结算账户
可行解决方案
1. 改用Place Details API获取完整信息
先通过Find Place API获取地点的place_id,再调用Place Details API获取包含电话号码的详细信息,这是Google官方推荐的获取地点详细数据的方式。修改后的代码如下:
import requests import json def get_place_details(api_key, place_id): # 调用Place Details API获取包含电话的详细信息 base_url = "https://maps.googleapis.com/maps/api/place/details/json?" fields = "name,formatted_phone_number,formatted_address" request_url = f"{base_url}place_id={place_id}&fields={fields}&key={api_key}" res = requests.get(request_url) return json.loads(res.text) def search_place(api_key, place): base_url = "https://maps.googleapis.com/maps/api/place/findplacefromtext/json?" inputtype = "textquery" # 仅获取匹配地点的place_id即可 fields = "place_id" locationbias = "ipbias" request_url = f"{base_url}input={place}&inputtype={inputtype}&fields={fields}&locationbias={locationbias}&key={api_key}" res = requests.get(request_url) return json.loads(res.text) api_key = "<my api key>" hotel_list = [ "White castle", "Mihilaka holiday homes", ] with open("hotel_numbers.txt", "w") as file: for hotel in hotel_list: search_data = search_place(api_key, hotel) if 'candidates' in search_data and search_data['candidates']: place_id = search_data['candidates'][0]['place_id'] details_data = get_place_details(api_key, place_id) if 'result' in details_data: name = details_data['result'].get('name', '') phone = details_data['result'].get('formatted_phone_number', "Can't find") file.write(f"{name}: {phone}\n") else: file.write(f"{hotel}: Can't find details\n") else: file.write(f"{hotel}: No matching place found\n")
2. 优化搜索参数与API配置
- 细化搜索关键词:添加城市或区域信息,比如
"White castle Colombo",提升匹配准确性 - 缩小位置范围:将
locationbias替换为更精确的圆形范围,例如circle:5000@6.9271,79.8612(科伦坡经纬度,半径5000米) - 检查API控制台:确保已启用Places API,API密钥无访问限制,配额充足且已绑定结算账户(免费配额有限,超出需付费)
3. 调试排查技巧
- 在代码中添加
print(data)语句,打印API返回的原始JSON数据,确认是无匹配结果还是结果中无电话号码字段 - 直接在浏览器中访问构造好的请求URL,查看返回内容,排查参数错误或API密钥有效性问题
内容的提问来源于stack exchange,提问作者Dineth De Silva
相关产品推荐
相关产品推荐

