【问题标题】:while using openweather.org api using for temperature and weather it shows an keyerror在使用 openweather.org api 用于温度和天气时,它显示一个 keyerror
【发布时间】:2021-11-21 21:26:08
【问题描述】:

在我的语音助手项目中,我想设置一个预测。因此我使用 openweather.org 的 api 密钥,我的代码如下

import requests
from os import *

api_address = "https://api.openweathermap.org/data/2.5/weather?id=bfbe606c8d661478b8132b49eee8051a"
json_data = requests.get(api_address).json()
# json_data = json_data.json()

def temp():
    temperature = round(json_data['main']['temp']-273.1)
    return temperature

def des():
    description = json_data["weather"][0]["description"]
    return description

print(temp())
print(des()) 

但这里的问题是控制台显示有关“keyerror”的错误:

line 9, in temp
    temperature = round(json_data['main']['temp']-273.1)

KeyError: 'main'

请给我建议任何可以让我摆脱这个问题的解决方案。

【问题讨论】:

  • 你确定有主属性吗?
  • 你调试过你的代码并查看你的 json_data 结构了吗?当我尝试你的代码时,我得到了 401 错误。好像您的 API 密钥还没有工作。他们建议在使用前等待几个小时。请在此处阅读:openweathermap.org/faq#error401
  • 我认为你需要在尝试访问里面的数据之前使用 json.load()
  • 想一想,您可能不应该在此处发布您的 API 密钥,因为它与您在 Openweather 上的个人帐户相关联。使用该 API 密钥完成的任何请求都将被追踪给您。我建议您删除该密钥并创建一个新密钥。
  • 是的,这是主要属性

标签: python python-3.x api dictionary openweathermap


【解决方案1】:

Open-Meteo 的创建者在这里。您可以使用不需要 API 密钥的 Open-Meteo API:

import requests
from os import *

api_address = "https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&current_weather=true"
json_data = requests.get(api_address).json()

def temp():
    temperature = json_data['current_weather']['temperature']
    return temperature

def des():
    description = json_data["current_weather"]["weathercode"]
    return description

print(temp())
print(des()) 

输出:

12.4
2

请注意输入正确的纬度和经度以获取您所在位置的预报

【讨论】:

  • 这确实有效。所以谢谢你。
猜你喜欢
  • 2021-06-02
  • 2018-08-31
  • 1970-01-01
  • 2016-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-05
  • 1970-01-01
相关资源
最近更新 更多