http://m.weather.com.cn/data/101010100.html
其中,最详细的信息来自第三个接口。上面url中的101010100是城市代码,这里是北京的城市代码。只需要改变城市代码,就可以得到所在城市的天气信息。
如,武汉的城市代码是101200101,所以所需要的url应该为 http://m.weather.com.cn/data/101200101.html,从而就可以读到天气的信息。
天气信息的数据结构是json,数据如下:
{"weatherinfo":{"city":"武汉","city_en":"wuhan","date_y":"2012年7月2日","date":"","week":"星期一","fchh":"11","cityid":"101200101","temp1":"35℃~27℃","temp2":"34℃~27℃","temp3":"34℃~27℃","temp4":"35℃~27℃","temp5":"35℃~27℃","temp6":"35℃~28℃","tempF1":"95℉~80.6℉","tempF2":"93.2℉~80.6℉","tempF3":"93.2℉~80.6℉","tempF4":"95℉~80.6℉","tempF5":"95℉~80.6℉","tempF6":"95℉~82.4℉","weather1":"多云","weather2":"多云","weather3":"多云","weather4":"多云","weather5":"多云","weather6":"多云","img1":"1","img2":"99","img3":"1","img4":"99","img5":"1","img6":"99","img7":"1","img8":"99","img9":"1","img10":"99","img11":"1","img12":"99","img_single":"1","img_title1":"多云","img_title2":"多云","img_title3":"多云","img_title4":"多云","img_title5":"多云","img_title6":"多云","img_title7":"多云","img_title8":"多云","img_title9":"多云","img_title10":"多云","img_title11":"多云","img_title12":"多云","img_title_single":"多云","wind1":"微风","wind2":"微风","wind3":"微风","wind4":"微风","wind5":"微风","wind6":"微风","fx1":"微风","fx2":"微风","fl1":"小于3级","fl2":"小于3级","fl3":"小于3级","fl4":"小于3级","fl5":"小于3级","fl6":"小于3级","index":"炎热","index_d":"天气炎热,建议着短衫、短裙、短裤、薄型T恤衫、敞领短袖棉衫等清凉夏季服装。","index48":"炎热","index48_d":"天气炎热,建议着短衫、短裙、短裤、薄型T恤衫、敞领短袖棉衫等清凉夏季服装。","index_uv":"中等","index48_uv":"中等","index_xc":"适宜","index_tr":"一般","index_co":"很不舒适","st1":"35","st2":"28","st3":"35","st4":"28","st5":"35","st6":"26","index_cl":"较适宜","index_ls":"适宜","index_ag":"不易发"}}
天气信息解释为:
具体的json数据结构的知识,我们下一篇文章介绍。
现在我们需要知道的是:json的数据结构和python中的字典很相似。
那么接下来的工作就是,如何用python去解析json数据结构中的信息。
实际上JSON就是Python字典的字符串表示,但是字典作为一个复杂对象是无法直接转换成定义它的代码的字符串(不能传递所以需要将其转换成字符串先),Python有一个叫simplejson的库可以方便的完成JSON的生成和解析,这个包已经包含在Python2.6中,就叫json 主要包含四个方法: dump和dumps(从Python生成JSON),load和loads(解析JSON成Python的数据类型)
dump和dumps的唯一区别是dump会生成一个类文件对象,dumps会生成字符串,同理load和loads分别解析类文件对象和字符串格式的JSON。
还有一点疑惑就是关于字符编码的,有待继续研究