初学Python---------------天气预报

来源:互联网 发布:达内linux视频 百度云 编辑:程序博客网 时间:2024/06/05 10:56

今天利用百度的天气预报API,实现了一个可以查询全国城市天气预报的小脚本。亲测可用:

#!\usr\bin\python#encoding:utf-8import sysimport urllib2from xml.dom import minidomak = '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.documentElementdef show(node):if not node.hasChildNodes():if node.nodeType == node.TEXT_NODE and node.data != '\n':tag_name = node.parentNode.tagNamecontent = node.data.replace('\n','')if tag_name == 'currentCity' or tag_name == 'date' or tag_name == 'weather' or tag_name == 'wind':print contentif tag_name == 'temperature':print contentprint '---------------------------'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)


0 0
原创粉丝点击