OpenWeatherMapAPI,如何获取临时数据?

2024-10-01 04:45:05 发布

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

使用Openweather JSON API,我从城市获取数据。我可以检索所有数据,我关注的数据是temp和dt_txt

我尝试过通过这样做来获取临时值,但不起作用:

import requests

def getCity():
    allCityName = ["London"]
    for cityName in allCityName:
        url = "http://api.openweathermap.org/data/2.5/forecast?q="+ cityName +"&appid="
        response = requests.get(url)
        data = response.json()
        print(data["main"]["temp"]

我尝试了许多组合,但似乎总是得到一个错误或没有结果。 任何帮助都将不胜感激


Tags: 数据importtxtapijsonurldataresponse
1条回答
网友
1楼 · 发布于 2024-10-01 04:45:05

也许你没有意识到这一点,但每个城市都会返回超过1条temp和dt_文本。所以,除非你知道你想要第一个,最后一个,或者中间的某个地方,你不能把它拔出来。或者,如果你想要它们,你必须把它们收集在一个列表中,例如

data = getCity()
for d in data['list']:
    print(d['main']['temp'])
    print(d['dt_txt'])

281.44
2020-12-15 06:00:00
281.33
2020-12-15 09:00:00
283.54
2020-12-15 12:00:00
283.19
2020-12-15 15:00:00
281.88
2020-12-15 18:00:00
281.4
2020-12-15 21:00:00
281.17
2020-12-16 00:00:00
281.59
2020-12-16 03:00:00
281.75
2020-12-16 06:00:00
281.95
2020-12-16 09:00:00
283.61
2020-12-16 12:00:00
282.86
2020-12-16 15:00:00
282.99
2020-12-16 18:00:00
283.17
2020-12-16 21:00:00
281.61
2020-12-17 00:00:00
281.19
2020-12-17 03:00:00
281.27
2020-12-17 06:00:00
280.81
2020-12-17 09:00:00
282.71
2020-12-17 12:00:00
282.64
2020-12-17 15:00:00
281.16
2020-12-17 18:00:00
282.16
2020-12-17 21:00:00
282.52
2020-12-18 00:00:00
283.4
2020-12-18 03:00:00
284.03
2020-12-18 06:00:00
283.86
2020-12-18 09:00:00
284.4
2020-12-18 12:00:00
284.19
2020-12-18 15:00:00
283.87
2020-12-18 18:00:00
284.21
2020-12-18 21:00:00
284.34
2020-12-19 00:00:00
284.53
2020-12-19 03:00:00
284.44
2020-12-19 06:00:00
283.48
2020-12-19 09:00:00
284.81
2020-12-19 12:00:00
284.55
2020-12-19 15:00:00
283.7
2020-12-19 18:00:00
283.33
2020-12-19 21:00:00
282.42
2020-12-20 00:00:00
281.76
2020-12-20 03:00:00

temps = [d['main']['temp'] for d in data['list']]

In [59]: print(temps)
[281.44, 281.33, 283.54, 283.19, 281.88, 281.4, 281.17, 281.59, 281.75, 281.95, 283.61, 282.86, 282.99, 283.17, 281.61, 281.19, 281.27, 280.81, 282.71, 282.64, 281.16, 282.16, 282.52, 283.4, 284.03, 283.86, 284.4, 284.19, 283.87, 284.21, 284.34, 284.53, 284.44, 283.48, 284.81, 284.55, 283.7, 283.33, 282.42, 281.76]

相关问题 更多 >