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

python获取天气预报程序第一版(齐齐哈尔市内一周天气)

2016-02-17 09:19 253 查看
利用中国国家气象局免费api接口实现的获取天气预报程序
from  xml.dom import minidom
from collections import namedtuple
from termcolor import colored
import sys
import urllib.request
#######着色程序
WEA = namedtuple('WEA','value color ')
Weather_Dict = {
'date':WEA('%s', 'green'),
'weather':WEA('%s', 'green'),
'low': WEA('%s', 'blue'),
'high': WEA('%s', 'cyan'),
'wind': WEA('%s', 'green'),
'wd': WEA('%s', yellow'),
'icon1': WEA('%s', 'yellow'),
'icon2': WEA('%s', 'blue')
}

URL = 'http://www.apifree.net/weather'
Query = {'泰来': '101050210',
'甘南': '101050204',
'齐齐哈尔': '101050201',
'富裕': '101050205',
'讷河': '101050202',
'克东': '101050209',
'拜泉': '101050207',
'龙江': '101050203',
'克山': '101050208',
'依安': '101050206'
}
def look(url):
result = urllib.request.urlopen(URL +'/'+ url +'.xml')
return result
#获取城市名称
def get_city(node):
c = node.getElementsByTagName('ws')[0]
#print(c.getAttribute('aqi'))
print(colored('city:%s aqi:%s' %(c.getAttribute('city'),c.getAttribute('aqi')),Weather_Dict['icon2'].color) )
#获取文本节点内容
def getText(nodelist):
rc = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return ''.join(rc)

###########下面的代码冗余度太大有待改进###########处理xnl文件
def read_xml(node):
fields = node.getElementsByTagName("w")
for field in fields:
handle_date(field.getElementsByTagName("date")[0])
handle_weather(field.getElementsByTagName("weather")[0])
handle_low(field.getElementsByTagName("low")[0])
handle_high(field.getElementsByTagName("high")[0])
handle_wind(field.getElementsByTagName("wind")[0])
handle_wd(field.getElementsByTagName("wd")[0])
handle_icon1(field.getElementsByTagName("icon1")[0])
handle_icon2(field.getElementsByTagName("icon2")[0])
def handle_date(date):
print(colored('date:%s'% getText(date.childNodes),Weather_Dict['date'].color))
def handle_weather(weather):
print(colored('weather:%s'% getText(weather.childNodes),Weather_Dict['weather'].color))
def handle_low(low):
print(colored('low:%s'% getText(low.childNodes),Weather_Dict['low'].color))
def handle_high(high):
print(colored('high:%s'% getText(high.childNodes),Weather_Dict['high'].color))
def handle_wind(wind):
print(colored('wind:%s'% getText(wind.childNodes),Weather_Dict['wind'].color))
def handle_wd(wd):
print(colored('wd:%s'% getText(wd.childNodes),Weather_Dict['wd'].color))
def handle_icon1(icon1):
print(colored('icon1:%s'% getText(icon1.childNodes),Weather_Dict['icon1'].color))
def handle_icon2(icon2):
print(colored('icon2:%s'% getText(icon2.childNodes),Weather_Dict['icon2'].color))
#################################################################################
def main():
qname = sys.argv[1]
if qname in Query.keys():
response = look(Query[qname])
dom = minidom.parse(response) #生成文档树对象
get_city(dom)
read_xml(dom)
if __name__=='__main__':
main()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: