尝试openweathermap python api教程时出现键错误“Main”

2024-05-11 12:44:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在尝试通过Python运行一个关于如何通过Python设置openweathermap的教程,但是我得到了一个关键错误,我想知道是否有人可以帮助我。在

我得到的错误是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 ")

Tags: keynameinapiurlcitybasemain