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

基于python的终端天气查询

2015-12-25 00:00 591 查看
摘要: 基于python的终端天气查询

一、 天气接口

网上搜了一个,最开始准备使用中国天气网的数据接口,但是需要注册,也行,注册就注册吧。
注册好了,又提示信息不完整,好吧,填写姓名、身份证...
最后,还要上传身份证信息,看到这我不想用它了,紧接着发现,还要填写使用该接口的服务器ip。
顿时,心中十万个那个啥呼啸而过...
这时想起百度的产品里有个API store,搜索了下,果然找到了合适的接口。
城市接口 http://apistore.baidu.com/microservice/cityinfo?cityname=城市名
{"errNum":0,"retMsg":"success","retData":{"cityName":"\u5317\u4eac","provinceName":"\u5317\u4eac","cityCode":"101010100","zipCode":"100000","telAreaCode":"010"}}


天气接口 http://apis.baidu.com/apistore/weatherservice/recentweathers?cityid=城市编码 该请求需要在header中添加apikey字段,该值可以在百度天气接口中获取。

二、 代码编写

#!/usr/bin/env python
#-*- coding:utf-8 -*-
import urllib, urllib2
import json, sys, re
def getCityCode(cityname, hooker=re.compile(r'"cityCode":"(\d+)"')):
city_url = 'http://apistore.baidu.com/microservice/cityinfo?cityname='
city_url = city_url + urllib.quote(cityname)
resp = urllib2.urlopen(city_url).read()
return hooker.findall(resp)[0]

def getWeatherInfo(citycode, headers={'apikey':'7328474baf90532437b4becdc5f65706'}):
weather_url = 'http://apis.baidu.com/apistore/weatherservice/recentweathers?cityid='
weather_url = weather_url + citycode
resp = urllib2.urlopen(urllib2.Request(weather_url, headers=headers))
return json.loads(resp.read())['retData']

def parseData(data, info=''):
for key in ('date', 'curTemp', 'type', 'lowtemp', 'hightemp', 'fengli'):
info = info + data[key] + '\t'
return info

if __name__ == '__main__':
j = getWeatherInfo(getCityCode('上海'))
for item in ([j['today']] + [dict(d,**{'curTemp':''}) for d in j['forecast']]):
print parseData(item)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息