1、中华万年历天气文件下载(json格式)。有如下两种:
http://wthrcdn.etouch.cn/weather_mini?city=深圳
通过城市名字获得天气数据
http://wthrcdn.etouch.cn/weather_mini?citykey=101070101
通过城市id获得天气数据
数据内容像下面这样
{"data":{"yesterday":{"date":"28日星期六","high":"高温 27℃","fx":"无持续风向","low":"低温 21℃","fl":"","type":"多云"},"city":"深圳","forecast":[{"date":"29日星期天","high":"高温 23℃","fengli":"","low":"低温 19℃","fengxiang":"无持续风向","type":"阴"},{"date":"30日星期一","high":"高温 26℃","fengli":"","low":"低温 21℃","fengxiang":"无持续风向","type":">小雨"},{"date":"31日星期二","high":"高温 27℃","fengli":"","low":"低温 23℃","fengxiang":"无持续风向","type":"雷阵雨"},{"date":"1日星期三","high":"高温 25℃","fengli":"","low":"低温 21℃","fengxiang":"东风","type":"阴"},{"date":"2日星期四","high":"高温 24℃","fengli":"","low":"低温 19℃","fengxiang":"东风","type":"阴"}],"ganmao":"虽然温度适宜但风力较大,
仍较易发生感冒,体质较弱的朋友请注意适当防护。","wendu":"21"},"status":1000,"desc":"OK"}
我感觉就是python的字典,数据提取按字典的方法就行了。
2、文件下载方法:
#文件下载地址
Download_addres='http://wthrcdn.etouch.cn/weather_mini?city=深圳'
#把下载地址发送给requests模块
f=requests.get(Download_addres)
#下载文件(原文保存)
with open("weather","wb") as code:
code.write(f.content)
3、数据处理。
dataJson=json.load(open('weather',encoding='UTF-8'))#读取天气文件
#提取天气相关信息
date=dataJson['data']['forecast'][0]['date']#读取日期
tianqi=dataJson['data']['forecast'][0]['type']#读取天气
low=dataJson['data']['forecast'][0]['low']#读取最低气温
high=dataJson['data']['forecast'][0]['high']#读取最高气温
fengxiang=dataJson['data']['forecast'][0]['fengxiang']#读取风向
fengli=dataJson['data']['forecast'][0]['fengli']#读取风力
c='深圳:'+tianqi#城市天气给变量C
d='气温:'+low[3:-1]+'到'+high[3:-1]+'℃'#气温给变量d
e='风力:'+re.findall('.*CDATA\[(.*)]]',fengli)[0]#风力给变量e
f='风向:'+fengxiang#风向给变量f
print(c)#显示城市天气
print(d)#显示气温
print(e)#显示风力
print(f)#显示风向
完整代码:
import requests,json,re #需要这三个库
#文件下载地址
Download_addres='http://wthrcdn.etouch.cn/weather_mini?city=深圳'
#把下载地址发送给requests模块
f=requests.get(Download_addres)
#下载文件(原文保存)
with open("weather","wb") as code:
code.write(f.content)
dataJson=json.load(open('weather',encoding='UTF-8'))#读取天气文件
#提取天气相关信息
date=dataJson['data']['forecast'][0]['date']#读取日期
tianqi=dataJson['data']['forecast'][0]['type']#读取天气
low=dataJson['data']['forecast'][0]['low']#读取最低气温
high=dataJson['data']['forecast'][0]['high']#读取最高气温
fengxiang=dataJson['data']['forecast'][0]['fengxiang']#读取风向
fengli=dataJson['data']['forecast'][0]['fengli']#读取风力
c='深圳:'+tianqi#城市天气给变量C
d='气温:'+low[3:-1]+'-'+high[3:-1]+'℃'#气温给变量d
e='风力:'+re.findall('.*CDATA\[(.*)]]',fengli)[0]#风力给变量e
f='风向:'+fengxiang#风向给变量f
print(date)显示日期
print(c)#显示城市天气
print(d)#显示气温
print(e)#显示风力
print(f)#显示风向
程序运行需要3个库,re\json\requests,需安装完成后上面代码才可以跑完。
程序运行结果如下图: