使用OpenWeather API获取天气时出现KeyError: 'main'报错如何解决
问题解决方法
问题根源
KeyError: 'main'是因为API请求失败,返回的响应JSON为错误提示结构,不存在main字段,错误原因有3个:
- API身份校验参数名错误,OpenWeather要求用
appid作为密钥参数,你代码里错写为id,请求未通过鉴权 - 缺少必选的位置查询参数,接口需要指定查询的城市/经纬度,当前请求没有传对应参数
- 没有做响应状态校验,直接对错误响应的JSON取字段导致报错
修复步骤
1. 修正API请求参数
调整请求链接,修改参数名id为appid,增加位置参数,示例用q=上海指定查询上海的天气,你可以替换为你需要的城市名,也可以换成lat+lon经纬度参数、city_id城市ID参数。
2. 增加请求状态校验
先判断HTTP状态码是否为200,再解析对应字段,避免报错。
3. 清理冗余导入
删除无用的from os import *导入语句。
修复后可运行代码
import requests # 修正参数:appid替换原id,增加q参数指定城市,加&units=metric直接返回摄氏度不需要自己换算 api_address = "https://api.openweathermap.org/data/2.5/weather?q=上海&appid=bfbe606c8d661478b8132b49eee8051a&units=metric" response = requests.get(api_address) # 先校验请求是否成功 if response.status_code != 200: print(f"请求失败,错误码:{response.status_code},错误信息:{response.text}") exit() json_data = response.json() def temp(): temperature = round(json_data['main']['temp']) return temperature def des(): description = json_data["weather"][0]["description"] return description print(temp()) print(des())
内容的提问来源于stack exchange,提问作者Rahul
相关产品推荐
相关产品推荐

