首页 > 解决方案 > 无法从 NOAA API 调用中获取数据

问题描述

我正在尝试按照网站上提到的方法访问气象站数据:https ://towardsdatascience.com/getting-weather-data-in-3-easy-steps-8dc10cc5c859我为此使用python。我还在学习python,我不知道为什么它会显示错误。我使用的代码行是:

r = requests.get('https://www.ncdc.noaa.gov/cdo-web/api/v2/data?datasetid=GHCND&datatypeid=\
                       TAVG&limit=1000&stationid=GHCND:USC00297461&startdate=2020-01-01&enddate=2020-10-22',
                       headers={'token':Token})
d = r.json()
avg_temps = [item for item in d['results'] if item['datatype']=='TAVG']

错误是:

KeyError                                  Traceback (most recent call last)
<ipython-input-85-c1a56919f6ab> in <module>()
      4 d = r.json()
      5 #get the item (average temperature) from the response
----> 6 avg_temps = [item for item in d['results'] if item['datatype']=='TAVG']

KeyError: 'results'

标签: pythonapinoaa

解决方案


你得到一个错误,因为你应该有这个

avg_temps = [item for item in d['results'] if item['datatype']=='TAVG']

而不是这个:

avg_temps = [item for item in d['results'] if d['datatype']=='TAVG']

区别item['datatype']d['datatype']


推荐阅读