You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python请求响应解析错误:天气API风速风向获取失败排查

问题排查:OpenWeatherMap预报风速获取失败

我正在编写一段代码片段,用于将风速和风向插入到更新电子墨水屏的大型脚本中。昨晚代码还能正常运行,但修改后就失效了,且未保存旧版本无法回溯。原本能输出类似13 / NW的结果,现在仅输出wind,问题出在尝试添加预报风速、修改print语句之后。

当前代码

import json
import requests

WEATHER_API = 'abcd1234'

def degreesToTextDesc(deg):
    if deg > 337.5: return "N"
    if deg > 292.5: return "NW"
    if deg > 247.5: return "W"
    if deg > 202.5: return "SW"
    if deg > 157.5: return "S"
    if deg > 122.5: return "SE"
    if deg >  67.5: return "E"
    if deg >  22.5: return "NE"
    return "N"


try:
    weather_response = requests.get("http://api.openweathermap.org/data/2.5/weather", params={"appid":WEATHER_API, "units":'imperial', "zip":'40217,us'}).json()
    forecast_response = requests.get("http://api.openweathermap.org/data/2.5/forecast", params={"appid":WEATHER_API, "units":'imperial', "zip":'40217,us'}).json()
    current_wind_speed = str(int(weather_response['wind']['speed']))
    current_wind_dir = str(degreesToTextDesc(weather_response['wind']['deg']))
    forecast_wind_speed = str(int(forecast_response['wind']['speed']))
    forecast_wind_dir = str(degreesToTextDesc(forecast_response['wind']['deg']))
    print(current_wind_speed + ' / ' + current_wind_dir + ' -> ' + forecast_wind_speed + ' / ' + forecast_wind_dir)
except Exception as error:
    print(error)

API返回示例

forecast_response(预报接口返回)

{'cod': '200', 'message': 0, 'cnt': 40, 'list': [{'dt': 1702101600, 'main': {'temp': 58.42, 'feels_like': 56.84, 'temp_min': 56.82, 'temp_max': 58.42, 'pressure': 1014, 'sea_level': 1014, 'grnd_level': 996, 'humidity': 61, 'temp_kf': 0.89}, 'weather': [{'id': 804, 'main': 'Clouds', 'description': 'overcast clouds', 'icon': '04n'}], 'clouds': {'all': 100}, 'wind': {'speed': 12.1, 'deg': 185, 'gust': 33.93}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'n'}, 'dt_txt': '2023-12-09 06:00:00'}]}

weather_response(当前天气接口返回)

{'coord': {'lon': -85.7404, 'lat': 38.2174}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'light rain', 'icon': '10d'}], 'base': 'stations', 'main': {'temp': 61.93, 'feels_like': 61.77, 'temp_min': 59.81, 'temp_max': 63.01, 'pressure': 1011, 'humidity': 84}, 'visibility': 10000, 'wind': {'speed': 13.8, 'deg': 190, 'gust': 21.85}, 'rain': {'1h': 0.43}, 'clouds': {'all': 100}, 'dt': 1702148181, 'sys': {'type': 2, 'id': 2000057, 'country': 'US', 'sunrise': 1702126073, 'sunset': 1702160571}, 'timezone': -18000, 'id': 0, 'name': 'Louisville', 'cod': 200}

问题原因

直接访问forecast_response['wind']会触发KeyError——预报接口的返回结构里,wind数据不在根节点下,而是嵌套在list数组的每一个预报条目里。当前代码的异常捕获会打印出错键名wind,这就是你看到的输出结果。

修复方案

需要先从list数组中取出目标预报时段的条目,再获取其中的wind数据。比如取第一个预报时段(最近的未来3小时):

修改代码中预报风速相关的行:

# 取第一个预报时段的风数据(可根据需求调整索引,每个条目间隔3小时)
forecast_wind_data = forecast_response['list'][0]['wind']
forecast_wind_speed = str(int(forecast_wind_data['speed']))
forecast_wind_dir = str(degreesToTextDesc(forecast_wind_data['deg']))

修复后的完整代码

import json
import requests

WEATHER_API = 'abcd1234'

def degreesToTextDesc(deg):
    if deg > 337.5: return "N"
    if deg > 292.5: return "NW"
    if deg > 247.5: return "W"
    if deg > 202.5: return "SW"
    if deg > 157.5: return "S"
    if deg > 122.5: return "SE"
    if deg >  67.5: return "E"
    if deg >  22.5: return "NE"
    return "N"


try:
    weather_response = requests.get("http://api.openweathermap.org/data/2.5/weather", params={"appid":WEATHER_API, "units":'imperial', "zip":'40217,us'}).json()
    forecast_response = requests.get("http://api.openweathermap.org/data/2.5/forecast", params={"appid":WEATHER_API, "units":'imperial', "zip":'40217,us'}).json()
    current_wind_speed = str(int(weather_response['wind']['speed']))
    current_wind_dir = str(degreesToTextDesc(weather_response['wind']['deg']))
    
    # 修正预报风数据的获取方式
    forecast_wind_data = forecast_response['list'][0]['wind']
    forecast_wind_speed = str(int(forecast_wind_data['speed']))
    forecast_wind_dir = str(degreesToTextDesc(forecast_wind_data['deg']))
    
    print(current_wind_speed + ' / ' + current_wind_dir + ' -> ' + forecast_wind_speed + ' / ' + forecast_wind_dir)
except Exception as error:
    print(error)

补充说明

如果需要获取特定时段的预报,比如未来12小时的,只需要调整list的索引即可:每个条目对应3小时的预报,索引0是最近的时段,索引4就是12小时后(4×3=12)。

内容的提问来源于stack exchange,提问作者pslaugh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 04:45:56