基于python的终端天气查询

时间:2022-05-15
本文章向大家介绍基于python的终端天气查询,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、 天气接口

网上搜了一个,最开始准备使用中国天气网的数据接口,但是需要注册,也行,注册就注册吧。

注册好了,又提示信息不完整,好吧,填写姓名、身份证...

最后,还要上传身份证信息,看到这我不想用它了,紧接着发现,还要填写使用该接口的服务器ip。

顿时,心中十万个那个啥呼啸而过...

这时想起百度的产品里有个API store,搜索了下,果然找到了合适的接口。

城市接口

http://apistore.baidu.com/microservice/cityinfo?cityname=城市名

{"errNum":0,"retMsg":"success","retData":{"cityName":"u5317u4eac","provinceName":"u5317u4eac","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)