1、首先是找到带有json文件的网址。网址:http://wthrcdn.etouch.cn/weather_mini?city=北京注意:这个网址的后面的地名可以自己更改,如http://wthrcdn.etouch.cn/weather_mini?city=上海对了,如果打开的页面是乱码,那是因为问个的显示编码方式不对,在网页单击鼠标右键,选择编码 ,选择Unicode(UTF-8),用的浏览器不一样,操作方式应该不一样,只要将网站的显示页面的编码方式改成utf-8就行了
2、导入模块importjson,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变量)importpprint#导入pprint模块ppr足毂忍珩int.pprint(weatherData)#漂亮打印出天气字典执行结果(我只截取了一部分图形,太长了) 从下面的图形可以看出‘data’是字典的第一个键,其值也是一个字典,这个字典中键'forecast'才是表示天气信息的。'date':表示日期......等 。这些应该都看得懂,就不浪费时间解释了......
6、接下来就是对这个字典(weatherData)的数据进行处理就是平时处理字典与列表的方式即可。举例:获取今天的天气:weatherData['data']['forecast'][0]['type']#输出>>'晴'获取今天的温度weatherData['data']['wendu'] #输出>>'16'
7、下面是获取天气的整个过程,我将源代码一起贴上:#!python3#coding:utf-8importjson,sys,r髫潋啜缅equests#输入地点weatherPlace=input("请输入天气地点:")ifweatherPlace=='E'orweatherPlace=='e':sys.exit(0);#关闭程序#下载天气JSONweatherJsonUrl="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)#以好看的形式打印字典与列表表格#importpprint#pprint.pprint(weatherData)w=weatherData['data']print("地点:%s"%w['city'])#日期date_a=[]#最高温与最低温highTemp=[]lowTemp=[]#天气weather=[]#进行五天的天气遍历foriinrange(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']+"℃") 上述代码在运行的时候要输入>> 地名<< ,如下图: