请利用SAX编写程序解析Yahoo的XML格式的天气预报,获取天气预报;
题目是廖雪峰老师的python教程中XML的练习。
本篇博文只是针对这一题目,没有做详细的介绍,如果看不懂可以在下面评论问我,我会及时回复的。
首先需要提到的是,在廖雪峰老师的练习测试中所给出的url我多次尝试,甚至还用了Postman进行访问都没有成功,因此如果有同学在测试过程中一直无法成功的话,可以直接复制我给出的XML,相比较来说简化了去访问这一步骤。
给出的xml是从一位前辈的博文中提取的,感谢。
# -*- coding:utf-8 -*-
from xml.parsers.expat import ParserCreate
weather_dict = {} # 定义天气字典
which_day = 0 # 哪一天
# 定义解析类 这三个函数在廖雪峰老师xml这一节中介绍了
# 包括三个主要函数:start_element(),end_element(),char_data()
class WeatherSaxHandler(object):
def start_element(self, name, attrs): # 定义start_element函数
global weather_dict, which_day
if name == 'yweather:location': # 判断并获取XML文档中地理位置信息
weather_dict['city'] = attrs['city'] # 将本行XML代码中'city'属性值赋予字典weather_dict中的'city'
weather_dict['country'] = attrs['country'] # 执行结束后此时,weather_dict={'city':'Beijing','country'='China'}
if name == 'yweather:forecast': # 同理获取天气预测信息
which_day += 1 # 第一天天气,获取气温、天气
if which_day == 1:
weather_today = {'text': attrs['text'],
'low': int(attrs['low']),
'high': int(attrs['high'])
}
weather_dict['today'] = weather_today # 此时weather_dict出现二维字典
# weather_dict={'city': 'Beijing', 'country': 'China', 'today': {'text': 'Partly Cloudy', 'low': 20, 'high': 33}}
elif which_day == 2: # 第二天相关信息
weather_today = {
'text': attrs['text'],
'low': int(attrs['low']),
'high': int(attrs['high'])
}
weather_dict['tomorrow'] = weather_today
# weather_dict={'city': 'Beijing', 'country': 'China', 'today': {'text': 'Partly Cloudy', 'low': 20, 'high': 33}, 'tomorrow': {'text': 'Sunny', 'low': 21, 'high': 34}}
def end_element(self, name): # end_element函数
pass
def char_data(self, text): # char_data函数
pass
def parse_weather(xml):
handler = WeatherSaxHandler()
parser = ParserCreate()
parser.StartElementHandler = handler.start_element
parser.EndElementHandler = handler.end_element
parser.CharacterDataHandler = handler.char_data
parser.Parse(xml)
return weather_dict
# XML文档,输出结果的数据来源
# 将XML文档赋值给data
data = r'''
Yahoo! Weather - Beijing, CN
Wed, 27 May 2015 11:00 am CST
-
39.91
116.39
Wed, 27 May 2015 11:00 am CST
'''
# 实例化类
weather = parse_weather(data)
# 检查条件是否为True
assert weather['city'] == 'Beijing', weather['city']
assert weather['country'] == 'China', weather['country']
assert weather['today']['text'] == 'Partly Cloudy', weather['today']['text']
assert weather['today']['low'] == 20, weather['today']['low']
assert weather['today']['high'] == 33, weather['today']['high']
assert weather['tomorrow']['text'] == 'Sunny', weather['tomorrow']['text']
assert weather['tomorrow']['low'] == 21, weather['tomorrow']['low']
assert weather['tomorrow']['high'] == 34, weather['tomorrow']['high']
# 打印到屏幕
print('Weather:', str(weather))
"这是测试结果"
Weather: {'city': 'Beijing', 'country': 'China', 'today': {'text': 'Partly Cloudy', 'low': 20, 'high': 33}, 'tomorrow': {'text': 'Sunny', 'low': 21, 'high': 34}}
希望能够帮助到大家,有什么问题可以 直接评论即可,如果不够详细的话也可以说,我会及时回复的。