尝试提取特定的API响应数据时出现KeyError

时间:2020-11-02 03:09:51

标签: python json api python-requests openweathermap

鉴于纬度和经度,我想提取并打印dt,温度,天气,湿度和风速。

我认为使用data = r.json()将使我能够像访问字典一样访问API响应,并能够使用print(r [“”])访问/打印我想要的元素,但是,我得到“ KeyError:'dt'”

from datetime import datetime
import json

import requests


def fetch_chart_data():
    # Fetch the data from the remote server, and raise an error if there was a
    # network problem or the server returned an error status code.
    result = requests.post(
        "https://aspren.dmac.adelaide.edu.au/c/portal/render_portlet",
        params={
            "p_l_id": "20734",
            "p_p_id": "chartportlet_WAR_chartportlet_INSTANCE_j3c9CC2nTCP9",
            "p_p_lifecycle": "0",
            "p_t_lifecycle": "0",
            "p_p_state": "normal",
            "p_p_mode": "view",
            "p_p_col_id": "column-1",
            "p_p_col_pos": "8",
            "p_p_col_count": "11",
            "p_p_isolated": "1",
            "currentURL": "/",
        }
    )
    result.raise_for_status()

    # Parse the HTML to get the JavaScript data object, and edit it to be valid
    # JSON. This way of doing it is liable to break if the structure of the
    # data or the HTML changes, but it works. Fancier ways of doing it involve
    # using HTML and JavaScript parsers.
    text = result.text
    chart_json = text[text.index("series:[{") + 7 : text.index("})})")]
    for key in ("name", "data", "visible"):
        chart_json = chart_json.replace(key, '"' + key + '"')

    # Convert the JSON data into a Python object. The dates in the raw data
    # are in Unix timestamp format (in thousandths of a second), so convert
    # them into Python datetime objects.
    chart_data = json.loads(chart_json)
    for disease_data in chart_data:
        for data_point in disease_data["data"]:
            data_point[0] = datetime.utcfromtimestamp(data_point[0] // 1000)

    return chart_data


if __name__ == "__main__":
    print(fetch_chart_data())

1 个答案:

答案 0 :(得分:0)

'dt'是'current'的成员,因此您必须通过2个键来访问它,如果您像下面那样打印json中的所有项目,就可以看到它:

def get_weather(lat,lon):

    import json
    import requests

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

    data = r.json()

    for k,v in data.items():
        print(k,v)
    
    current = data['current']
    print(current['dt'])

get_weather(33,44)