【问题标题】:Key Error 'Main' when trying an openweathermap python api tutorial尝试 openweathermap python api 教程时出现关键错误“主要”
【发布时间】: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


【解决方案1】:

以下作品:

import requests

OPEN_WEATHER_MAP_APIKEY = '<your key>'

def get_weather_data_by_location( lat, long):
    url = f'https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={long}&appid={OPEN_WEATHER_MAP_APIKEY}&units=metric'
    print(f"Getting data via {url}")
    r = requests.get(url)
    return r.json()
    if r.status_code == 200:
        return r.json()
    else:
        return None

if __name__ == '__main__':
    print("Getting Weather Data")
    print( get_weather_data_by_location( '22.300910042194783', '114.17070449064359') )

我有一个打开天气图的初学者指南,你可以在这里查看:https://pythonhowtoprogram.com/get-weather-forecasts-and-show-it-on-a-chart-using-python-3/

【讨论】:

    猜你喜欢
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2022-01-04
    相关资源
    最近更新 更多