1

我只想提取 API 响应的几个部分并打印它们。

当我运行这个:

def get_weather(lat,lon):

    import requests

    r = requests.post('https://api.openweathermap.org/data/2.5/onecall?lat={}&lon={}&exclude=hourly,daily&appid=92d93ccc6ac5587d35d3ccc4479083a1'.format(lat,lon))

    print(r.text)

get_weather(33,44)

API 响应显示为:

{"lat":33,"lon":44,"timezone":"Asia/Baghdad","timezone_offset":10800,"current":{"dt":1604279014,"sunrise":1604287381,"sunset":1604326320,"temp":295.15,"feels_like":290.63,"pressure":1015,"humidity":35,"dew_point":279,"uvi":4.16,"clouds":0,"visibility":10000,"wind_speed":5.1,"wind_deg":140,"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}]}}
Running: python (cwd=C:\Users\Daddy\Desktop\Cisco Problems\weatherForecast.py pid=6528). Exited with code=0 in 0.64 seconds.

因为我只想要 dt、temp、weather、湿度和 wind_speed,所以我在我的代码中添加了打印语句:

def get_weather(lat,lon):

    import requests

    r = requests.post('https://api.openweathermap.org/data/2.5/onecall?lat={}&lon={}&exclude=hourly,daily&appid=92d93ccc6ac5587d35d3ccc4479083a1'.format(lat,lon))

    print(r["dt"])
    print(r["temp"])
    print(r["weather"])
    print(r["humidity"])
    print(r["wind_speed"])

get_weather(33,44)

我现在收到此错误:

TypeError: 'Response' object is not subscriptable
4

1 回答 1

0

使用它来获取数据并像字典一样访问它:

data = r.json()
dt = data["dt"]
temp = data["temp"]
于 2020-11-02T01:18:10.030 回答