【发布时间】:2019-10-15 23:57:49
【问题描述】:
我目前正在尝试学习如何通过 Python 设置 openweathermap 的教程,但我遇到了 KeyError,我想知道是否有人可以帮助我。
我得到的错误是 KeyError: 'main'
在实际代码中,我已将其放入我的 API,但出于显而易见的原因将其取出。
api_key = ""
base_url = "http://api.openweathermap.org/data/2.5/weather?"
city_name = input("Enter city name : ")
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
response = requests.get(complete_url)
x = response.json()
if x["cod"] != "404":
y = x["main"]
current_temperature = y["temp"]
current_pressure = y["pressure"]
current_humidiy = y["humidity"]
z = x["weather"]
weather_description = z[0]["description"]
print(" Temperature (in kelvin unit) = " +
str(current_temperature) +
"\n atmospheric pressure (in hPa unit) = " +
str(current_pressure) +
"\n humidity (in percentage) = " +
str(current_humidiy) +
"\n description = " +
str(weather_description))
else:
print(" City Not Found ")
【问题讨论】:
-
添加
print(x)输出 -
您好 :) 抱歉,您的意思是让我在代码中包含 print(x)?
-
x = response.json()之后 -
好像是打印出JSON格式的天气信息,但还是显示KeyError。
-
添加信息;它没有
main
标签: python python-3.x api openweathermap