树莓派3调用MBTA API遇异常:红线请求报TypeError错误
使用树莓派3连接MBTA API
我用树莓派3调用MBTA交通API获取站点ID的更新信息,此前代码运行正常,但近日仅调用红线接口时出现问题,执行脚本时报错:
Traceback (most recent call last): File "APItest.py", line 23, in <module> currentstop[i] = stop_name(test[i]['id']) TypeError: 'NoneType' object is not subscriptable
调用蓝线站点信息时代码可正常运行,只需将变量line改为'Blue',其余代码完全不变。以下是调用红线的Python3代码:
import requests import json from APIstops import stop_name APIkey = '--------------------------' # 我的个人API密钥 line = 'Red' # 先测试红线 URL2 = "https://api-v3.mbta.com/vehicles?filter[route]=" + line + "&api_key=" + APIkey # 红线专用调用URL vehicles = requests.get(URL2) # 从API获取车辆数据 dataV = vehicles.text # 转为文本格式 parse_json = json.loads(dataV) # 解析为JSON格式 MBTAV = parse_json['data'] # 创建解析后的数据数组 vehicle_locals = dict() # 创建存储红线车辆当前位置的字典 test = dict() for vehicle in MBTAV: vehicle_locals[vehicle['id']] = vehicle['relationships']['stop']['data'] # 存储每条线路各列车的当前停靠站 #print(vehicle_locals) for i in range(0 , len(vehicle_locals)): test[i] = list(vehicle_locals.values())[i] print(test[0]['id']) currentstop = [None] * len(vehicle_locals) for i in range(0, len(vehicle_locals)): currentstop[i] = stop_name(test[i]['id']) print(currentstop)
我对比了红线和蓝线的API结构,未发现差异,不知问题所在,寻求解决方法。
红线MBTA API接口:https://api-v3.mbta.com/vehicles?filter[route]=Red
蓝线MBTA API接口:https://api-v3.mbta.com/vehicles?filter[route]=Blue
问题原因与解决方法
报错的核心原因是:红线部分车辆的API返回数据中,relationships.stop.data为None(比如列车正处于区间行驶状态,未停靠任何站点),而蓝线返回的所有车辆都有有效的停靠站数据,因此之前未触发错误。当代码尝试对None取值['id']时,就会抛出'NoneType' object is not subscriptable错误。
修复方案1:过滤无停靠站数据的车辆
在收集车辆停靠站数据时,直接跳过stop.data为None的条目:
for vehicle in MBTAV: stop_data = vehicle['relationships']['stop']['data'] if stop_data is not None: # 仅保留有有效停靠站数据的车辆 vehicle_locals[vehicle['id']] = stop_data
修复方案2:处理None值,避免报错
如果需要保留所有车辆(包括无停靠站的),则在调用stop_name前先判断数据是否有效:
currentstop = [] for stop_data in vehicle_locals.values(): if stop_data is not None: currentstop.append(stop_name(stop_data['id'])) else: currentstop.append('无当前停靠站') # 或设置为None等默认值
优化建议:简化代码逻辑
原代码中的test字典完全多余,可以直接遍历vehicle_locals.values(),避免索引循环的冗余操作,让代码更简洁易维护。
内容的提问来源于stack exchange,提问作者Devon Ricken
相关产品推荐
相关产品推荐

