如何通过Python调用Walk Score API获取美国地址的步行评分?
解决Walk Score API请求失败的问题
问题描述
尝试通过Walk Score API获取美国地址的步行评分,使用以下Python脚本时持续收到「Failed to fetch Walk Score...」错误,无有效结果返回:
import requests # Define your Walk Score API key API_KEY = 'XXXXXXXX' # Define the address for which you want to get the Walk Score address = "450 Wilson Avenue, Morgantown, WV, 26505" # Define the base URL for the Walk Score API base_url = 'http://api.walkscore.com/score' # Prepare parameters for the API request params = { 'format': 'json', 'address': address, 'lat': '', 'lon': '', 'transit': '1', 'bike': '1', 'wsapikey': API_KEY } # Make the API request response = requests.get(base_url, params=params) # Check if the request was successful if response.status_code == 200: # Extract the Walk Score from the response data = response.json() walk_score = data['walkscore'] print(f"Walk Score for {address}: {walk_score}") else: print(f"Failed to fetch Walk Score for address: {address}")
可能的原因及修复方案
1. 切换为HTTPS协议
Walk Score API要求使用HTTPS发起请求,原脚本中的http协议会导致请求被拒绝。修改base_url:
base_url = 'https://api.walkscore.com/score'
2. 移除无效的经纬度参数
脚本中lat和lon设为空字符串,会干扰API的地址解析逻辑。如果没有经纬度数据,直接移除这两个参数:
params = { 'format': 'json', 'address': address, 'transit': '1', 'bike': '1', 'wsapikey': API_KEY }
若能获取到目标地址的经纬度,填入有效值可进一步提升请求成功率。
3. 验证API密钥有效性
确保API_KEY替换为从Walk Score官方获取的真实有效密钥,密钥需完成激活且未超出调用限额。
4. 增强错误排查能力
在错误分支中打印API返回的具体错误信息,便于精准定位问题:
else: print(f"Failed to fetch Walk Score for address: {address}") print(f"Status code: {response.status_code}") print(f"API response: {response.text}")
修复后的完整脚本
import requests # Replace with your valid Walk Score API key API_KEY = 'your_real_api_key_here' address = "450 Wilson Avenue, Morgantown, WV, 26505" base_url = 'https://api.walkscore.com/score' params = { 'format': 'json', 'address': address, 'transit': '1', 'bike': '1', 'wsapikey': API_KEY } response = requests.get(base_url, params=params) if response.status_code == 200: data = response.json() # 处理可能的字段缺失情况 walk_score = data.get('walkscore', 'N/A') transit_score = data.get('transit', {}).get('score', 'N/A') bike_score = data.get('bike', {}).get('score', 'N/A') print(f"Walk Score for {address}: {walk_score}") print(f"Transit Score: {transit_score}") print(f"Bike Score: {bike_score}") else: print(f"Failed to fetch Walk Score for address: {address}") print(f"Status code: {response.status_code}") print(f"API response: {response.text}")
内容的提问来源于stack exchange,提问作者Serkan Varol
相关产品推荐
相关产品推荐

