今天利用百度的天气预报API,实现了一个可以查询全国城市天气预报的小脚本。亲测可用:
#!\usr\bin\python
#encoding:utf-8
import sys
import urllib2
from xml.dom import minidom
ak = '6VmgXqokxQfh7tGFlPQKpLjQ'
url = 'http://api.map.baidu.com/telematics/v3/weather?'
def get_response(location):
return urllib2.urlopen(url + 'location=' + location + '&ak=' + ak)
def read_xml(xml):
dom = minidom.parse(xml)
return dom.documentElement
def show(node):
if not node.hasChildNodes():
if node.nodeType == node.TEXT_NODE and node.data != '\n':
tag_name = node.parentNode.tagName
content = node.data.replace('\n','')
if tag_name == 'currentCity' or tag_name == 'date' or tag_name == 'weather' or tag_name == 'wind':
print content
if tag_name == 'temperature':
print content
print '---------------------------'
else:
for e in node.childNodes:
show(e)
if __name__ == '__main__':
if len(sys.argv) != 2:
print 'how to use:'
print 'python weather.py location'
sys.exit()
else:
location = sys.argv[1]
root = read_xml(get_response(location))
show(root)
本文介绍了一款利用百度天气预报API开发的小脚本,该脚本能够查询全国城市的天气情况。通过Python语言实现了对API的调用及解析返回的XML数据。
2547

被折叠的 条评论
为什么被折叠?



