python 利用json获取5天的天气

2025-10-22 18:31:56

1、首先是找到带有json文件的网址。

网址:  http://wthrcdn.etouch.cn/weather_mini?city=北京

注意:这个网址的后面的地名可以自己更改,如http://wthrcdn.etouch.cn/weather_mini?city=上海

对了,如果打开的页面是乱码,那是因为问个的显示编码方式不对,在网页单击鼠标右键,选择编码  ,选择 Unicode(UTF-8),用的浏览器不一样,操作方式应该不一样,只要将网站的显示页面的编码方式改成utf-8就行了

python 利用json获取5天的天气

2、导入模块

import json, requests  

这两个模块是必须的,json可以用来将网页的json解析成python能识别的字典表示。

requests模块用来获取下载网站,即json的网站页面,用来方便处理

3、导入链接,获取页面

weatherJsonUrl = "http://wthrcdn.etouch.cn/weather_mini?city=北京"  #将链接定义为一个字符串  

response = requests.get(weatherJsonUrl)      #获取并下载页面,其内容会保存在respons.text成员变量里面  

response.raise_for_status() #这句代码的意思如果请求失败的话就会抛出异常,请求正常就上面也不会做  

4、解析json文件(即上一步的成员变量respons.text)

#将json文件格式导入成python的格式  

weatherData = json.loads(response.text)  

5、使用漂亮打印pprint模块打印转换后的python字典(weatherData变量)

import pprint               #导入pprint模块  

pprint.pprint(weatherData)  #漂亮打印出天气字典 

执行结果(我只截取了一部分图形,太长了)

    从下面的图形可以看出‘data’是字典的第一个键,其值也是一个字典,这个字典中键'forecast'才是表示天气信息的。

'date':表示日期 ......等 。这些应该都看得懂,就不浪费时间解释了......

python 利用json获取5天的天气

6、接下来就是对这个字典(weatherData)的数据进行处理

就是平时处理字典与列表的方式即可。

举例:

获取今天的天气:

weatherData['data']['forecast'][0]['type']  

#输出>> '晴'  

获取今天的温度

weatherData['data']['wendu']  

#输出>> '16'  

7、下面是获取天气的整个过程,我将源代码一起贴上:

#!python3  

#coding:utf-8  

import json, sys, requests  

   

#输入地点  

weatherPlace = input("请输入天气地点:")  

if weatherPlace == 'E' or weatherPlace == 'e':  

    sys.exit(0);    #关闭程序  

#下载天气JSON  

weatherJsonUrl = "http://wthrcdn.etouch.cn/weather_mini?city=%s" % (weatherPlace)  

response = requests.get(weatherJsonUrl)  

try:  

    response.raise_for_status()  

except:  

    print("网址请求出错")  

      

#将json文件格式导入成python的格式  

weatherData = json.loads(response.text)  

   

#以好看的形式打印字典与列表表格  

#import pprint  

#pprint.pprint(weatherData)  

   

w = weatherData['data']  

print("地点:%s" % w['city'])  

   

#日期  

date_a = []  

#最高温与最低温  

highTemp = []  

lowTemp = []  

#天气  

weather = []  

#进行五天的天气遍历  

for i in range(len(w['forecast'])):  

    date_a.append(w['forecast'][i]['date'])  

    highTemp.append(w['forecast'][i]['high'])  

    lowTemp.append(w['forecast'][i]['low'])  

    weather.append(w['forecast'][i]['type'])  

      

    #输出  

    print("日期:" + date_a[i])  

    print("\t温度:最" + lowTemp[i] + '℃~最' + highTemp[i] + '℃')  

    print("\t天气:" + weather[i])  

    print("")  

      

print("\n今日着装:" + w['ganmao'])  

print("当前温度:" + w['wendu'] + "℃")  

上述代码在运行的时候要输入 >>  地名 <<  ,如下图:

python 利用json获取5天的天气

python 利用json获取5天的天气

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢