【发布时间】: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