您的位置:首页 > 编程语言 > Python开发

python调用中国天气网的公用API获取天气信息

2013-05-13 17:06 281 查看
闲来无事想搞一下天气API,大致查了一下,国内比较好的还是中国天气网(中国气象台)的,门户网站有新浪和腾迅(搜搜),其他有一些小网站担心不稳定,所以没有用。

最简单的脚本。发送请求获取JSON并解析,简单地输出到屏幕上。

这里只用到了北京地区,其他地区需要将URL地址中的相关代码替换掉。这些代码可以在下面的参考链接中查到。

截屏如下,又有乱码,没有办法,python的乱码太恶心了,在IDLE里运行是正常的,凑合吧:



参考链接:
http://www.weste.net/2012/8-23/84850.html
#! /usr/bin/python
# coding = utf-8

# ToDo: get weather info from weather.com.cn
# Author: Steven
# Date: 2013/05/13

import urllib2
import json

# get weather html and parse to json
weatherHtml = urllib2.urlopen('http://m.weather.com.cn/data/101010100.html').read()
weatherJSON = json.JSONDecoder().decode(weatherHtml)
weatherInfo = weatherJSON['weatherinfo']

# print weather info
print '城市:\t', weatherInfo['city']
print '时间:\t', weatherInfo['date_y']
print '24小时天气:'
print '温度:\t', weatherInfo['temp1']
print '天气:\t', weatherInfo['weather1']
print '风速:\t', weatherInfo['wind1']
print '紫外线:\t', weatherInfo['index_uv']
print '穿衣指数:\t', weatherInfo['index_d']
print '48小时天气:'
print '温度:\t', weatherInfo['temp2']
print '天气:\t', weatherInfo['weather2']
print '风速:\t', weatherInfo['wind2']
print '紫外线:\t', weatherInfo['index48_uv']
print '穿衣指数:\t', weatherInfo['index48_d']
print '72小时天气:'
print '温度:\t', weatherInfo['temp3']
print '天气:\t', weatherInfo['weather3']
print '风速:\t', weatherInfo['wind3']
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: