在Tkinter中调用OpenWeatherMap API无法获取温度的问题
问题:OpenWeatherMap API温度数据提取失败
我用OpenWeatherMap API获取城市温度时失败了,能正常拿到城市名称,但温度等数据取不到,应该是数据提取方式错了,但找不到问题在哪。
我的代码
def format_response(weather): try: name = weather['city']['name'] temperature = weather['main']['temp'] final_str = f'City: {name} \n Temperature {temperature}' except: final_str = 'There was a problem retrieving that information' return final_str
API响应示例(与控制台输出一致)
{ "cod": "200", "message": 0, "cnt": 40, "list": [ { "dt": 1647345600, "main": { "temp": 286.88, "feels_like": 285.93, "temp_min": 286.74, "temp_max": 286.88, "pressure": 1021, "sea_level": 1021, "grnd_level": 1018, "humidity": 62, "temp_kf": 0.14 }, "weather": [ { "id": 804, "main": "Clouds", "description": "overcast clouds", "icon": "04d" } ], "clouds": { "all": 85 }, "wind": { "speed": 3.25, "deg": 134, "gust": 4.45 }, "visibility": 10000, "pop": 0, "sys": { "pod": "d" }, "dt_txt": "2022-03-15 12:00:00" }, { "dt": 1647356400, "main": { "temp": 286.71, "feels_like": 285.77, "temp_min": 286.38, "temp_max": 286.71, "pressure": 1021, "sea_level": 1021, "grnd_level": 1017, "humidity": 63, "temp_kf": 0.33 }, "weather": [ { "id": 804, "main": "Clouds", "description": "overcast clouds", "icon": "04d" } ], "clouds": { "all": 90 }, "wind": { "speed": 3.34, "deg": 172, "gust": 4.03 }, "visibility": 10000, "pop": 0, "sys": { "pod": "d" }, "dt_txt": "2022-03-15 15:00:00" }, ... ], "city": { "id": 2643743, "name": "London", "coord": { "lat": 51.5073, "lon": -0.1277 }, "country": "GB", "population": 1000000, "timezone": 0, "sunrise": 1647324903, "sunset": 1647367441 } }
解决方案
问题出在数据结构层级:你调用的是5天天气预报API,main字段不在响应顶层,而是嵌套在list数组的每个元素里。直接取weather['main']['temp']会因找不到字段报错。
如果要获取第一个时段的温度,修改代码如下:
def format_response(weather): try: name = weather['city']['name'] # 从list数组第一个元素中提取温度 temperature = weather['list'][0]['main']['temp'] # 可选:将开尔文温度转为摄氏度 temperature_c = round(temperature - 273.15, 2) final_str = f'城市: {name} \n 温度: {temperature_c}°C' except KeyError as e: final_str = f'获取信息出错: 缺少字段 {e}' except Exception as e: final_str = f'获取信息出错: {str(e)}' return final_str
补充说明
list数组的每个元素对应不同时间点的天气数据,list[0]是返回结果中最早的时段数据- OpenWeatherMap默认返回开尔文温度,转摄氏度需减去273.15
- 替换泛用
except为具体异常捕获,便于定位问题
内容的提问来源于stack exchange,提问作者Josborne
相关产品推荐
相关产品推荐

