【问题标题】:KeyError in Weather API Response天气 API 响应中的 KeyError
【发布时间】:2021-06-03 03:51:01
【问题描述】:

我正在制作一个 python 程序,它告诉天气,但遇到以下错误

请告诉如何纠正?

代码

import requests
import json

api = "<MY_API_KEY>"
BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
print("for which city?")
CITY = input("city?: ")
URL = BASE_URL + "q=" + CITY + "&appid=" + api

response = requests.get(URL)
if __name__ == "__main__":
    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: {temperature}")
    print(f"Humidity: {humidity}")
    print(f"Pressure: {pressure}")
    print(f"Weather Report: {report[0]['description']}")

终端

PS C:\Users\mamta\Documents\PythonPanti\JARVISprj>  c:; cd 'c:\Users\mamta\Documents\PythonPanti\JARVISprj'; & 'C:\Users\mamta\AppData\Local\Programs\Python\Python39\python.exe' 'c:\Users\mamta\.vscode\extensions\ms-python.python-2021.5.842923320\pythonFiles\lib\python\debugpy\launcher' 
'53873' '--' 'c:\Users\mamta\Documents\PythonPanti\JARVISprj\exp.py'
for which city?
city?: Delhi
Traceback (most recent call last):
  File "c:\Users\mamta\Documents\PythonPanti\JARVISprj\exp.py", line 13, in <module>
    main = data['main']
KeyError: 'main'

【问题讨论】:

  • 检查您的 API Key,它似乎无效。此外,切勿与任何人共享您的 API 密钥,尤其是不要在这样的公共论坛上
  • 我不确定分享您的 API 密钥是否明智。关于 KeyError - 它只是告诉您响应对象中没有“主”键。我建议打印“数据”。
  • @chmielcode 我运行了查询,这是一个 API 密钥错误。查看回复here
  • 你的代码是完美的,我看到的唯一问题是当你输入任何垃圾值时。 Notebook
  • 好的,谢谢,谢谢(你为什么要两次)

标签: python keyerror weather


【解决方案1】:

您的代码非常好,我看到的唯一问题是当您输入任何垃圾值时。您需要进行错误处理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-03
    • 2022-12-18
    • 1970-01-01
    • 2011-12-09
    • 1970-01-01
    • 2020-05-30
    相关资源
    最近更新 更多