网上找的代码,只有几行,但想取值方便点,结果因为json双层嵌套,想去除第一层,不懂弄了很久,原来是json含有空格,不是规范json,无法转为python数组,又认识到,有空格时无法转换时,可以直接用变量.json来操作。

import requests
import json
def Weather_Forecast():
    #网站各城市代码,打开各地天气后,可以在浏览器网址中看到
    num = '101210101'#杭州代码
    #网站api接口,GET后返回天气数据
    r = requests.get('http://www.weather.com.cn/data/cityinfo/{}.html'.format(num))
    #转为utf-8格式,不然会乱码
    r.encoding = 'utf-8'
    #返回的数据有空格,不是规范json代码 需要去除多余空格
    r = json.dumps(r.json(), separators=(',', ':'))
    #转为python数组
    r = json.loads(r)
    #得到的数据{'weatherinfo': {'city': '杭州', 'cityid': '101210101', 'temp1': '17℃', 'temp2': '27℃', 'weather': '暴雨', 'img1': 'n10.gif', 'img2': 'd10.gif', 'ptime': '18:00'}}
    #去除第一个‘weatherinfo’,去不去都可以,只是不去,下面取值要变成:r['weatherinfo']['city']
    r = r['weatherinfo']#这个是dict 键值对的取法

    print(r)
    #print测试得到:{'city': '杭州', 'cityid': '101210101', 'temp1': '17℃', 'temp2': '27℃', 'weather': '暴雨', 'img1': 'n10.gif', 'img2': 'd10.gif', 'ptime': '18:00'}

    ##############################################
    #以下这代码是因为之前没有去除空格,转不了python数组,也可以使用,直接把变量按json操作,
    # r = r.json()['weatherinfo']
    # print(r)
    #######################################################
    #找到需要的数据,打印输出,输出结果为
    #城市:杭州
    #温度:17℃到27℃
    #天气:暴雨
    print('城市:' + r['city'] + '\n' + '温度:' + r['temp1'] + '到' + r['temp2'] + '\n' + '天气:' + r['weather'])
    return

if __name__ == '__main__':
    Weather_Forecast()
最后修改:2020 年 10 月 11 日
如果觉得我的文章对你有用,请随意赞赏