Python调用OpenWeather天气API出现KeyError: 'main'错误如何解决?
问题原因
出现KeyError: 'main'是因为接口请求失败,返回的响应数据不包含main字段,大部分情况是以下两种原因:
- 你没有把代码里的
<MY_API_KEY>替换为自己在openweathermap平台申请的有效API密钥 - 网络请求异常、城市名拼写错误、API密钥权限异常导致接口返回了错误格式的响应,你直接读取了不存在的字段
修复方案
- 先替换API密钥:去openweathermap平台申请免费密钥后,替换代码里的
<MY_API_KEY>字符串 - 新增请求状态校验,不要直接读取响应字段,修改后的代码如下:
import requests api = "替换为你自己的实际API密钥" BASE_URL = "https://api.openweathermap.org/data/2.5/weather?" if __name__ == "__main__": print("for which city?") CITY = input("city?: ") # 加units=metric可以直接返回摄氏度温度,不需要额外单位转换 URL = BASE_URL + "q=" + CITY + "&appid=" + api + "&units=metric" response = requests.get(URL) # 先判断请求是否成功再读取返回数据 if response.status_code == 200: data = response.json() main = data['main'] temperature = main['temp'] humidity = main['humidity'] pressure = main['pressure'] report = data['weather'] print(f"{CITY:-^30}") print(f"温度: {temperature}℃") print(f"湿度: {humidity}%") print(f"气压: {pressure}hPa") print(f"天气情况: {report[0]['description']}") else: # 打印错误信息方便排查问题 print(f"请求失败,状态码:{response.status_code}") print(f"错误信息:{response.text}")
额外说明
如果请求返回状态码为401,说明你的API密钥无效或者还没激活,openweathermap的免费密钥申请后通常需要1-2小时才会正式生效;如果返回404,说明你输入的城市名平台无法识别,可以尝试加上国家后缀,比如Delhi,IN。
内容的提问来源于stack exchange,提问作者Arnav Shukla
相关产品推荐
相关产品推荐

