基于python的终端天气查询
2015-12-25 00:00
591 查看
摘要: 基于python的终端天气查询
注册好了,又提示信息不完整,好吧,填写姓名、身份证...
最后,还要上传身份证信息,看到这我不想用它了,紧接着发现,还要填写使用该接口的服务器ip。
顿时,心中十万个那个啥呼啸而过...
这时想起百度的产品里有个API store,搜索了下,果然找到了合适的接口。
城市接口 http://apistore.baidu.com/microservice/cityinfo?cityname=城市名
天气接口 http://apis.baidu.com/apistore/weatherservice/recentweathers?cityid=城市编码 该请求需要在header中添加apikey字段,该值可以在百度天气接口中获取。
一、 天气接口
网上搜了一个,最开始准备使用中国天气网的数据接口,但是需要注册,也行,注册就注册吧。注册好了,又提示信息不完整,好吧,填写姓名、身份证...
最后,还要上传身份证信息,看到这我不想用它了,紧接着发现,还要填写使用该接口的服务器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)
相关文章推荐
- python用sql的limit语句进行分页
- Python 包管理
- PYTHON 学习第九课
- Windows Python IDEL编译器自动忽略'\r'及简单进度条的实现
- Python2.7 NumPy和PIL模块安装
- 零基础入门学习Python(19):对象(4)组合、绑定
- 进击python第一篇:相遇
- python之模块py_compile用法(将py文件转换为pyc文件)
- Python爬虫 - 登录csdn
- 使用Pycharm安装Python第三方库
- Python第三方库安装技巧
- 【转】Python计算器小程序及文件IO
- python之模块pprint之常见用法
- 为Python安装pip工具
- python之模块poplib之常见用法
- 为Python安装easy_install工具
- python中__getitem__, __setitem__, __delitem__的使用
- python面向对象具体解释(上)
- Python爬虫学习系列教程
- Python爬虫入门八之Beautiful Soup的用法