請利用SAX編寫程式解析Yahoo的XML格式的天氣預報,獲取天氣預報——python學習筆記

Arrow and Bullet發表於2019-01-05

1. 題目:

請利用SAX編寫程式解析Yahoo的XML格式的天氣預報,獲取天氣預報;

題目是廖雪峰老師的python教程中XML的練習。
本篇博文只是針對這一題目,沒有做詳細的介紹,如果看不懂可以在下面評論問我,我會及時回覆的。

2. 程式碼如下:

首先需要提到的是,在廖雪峰老師的練習測試中所給出的url我多次嘗試,甚至還用了Postman進行訪問都沒有成功,因此如果有同學在測試過程中一直無法成功的話,可以直接複製我給出的XML,相比較來說簡化了去訪問這一步驟。
給出的xml是從一位前輩的博文中提取的,感謝。

2.1 參考程式碼(一位前輩的程式碼)

# -*- 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'''<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<rss version="2.0" xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
    <channel>
        <title>Yahoo! Weather - Beijing, CN</title>
        <lastBuildDate>Wed, 27 May 2015 11:00 am CST</lastBuildDate>
        <yweather:location city="Beijing" region="" country="China"/>
        <yweather:units temperature="C" distance="km" pressure="mb" speed="km/h"/>
        <yweather:wind chill="28" direction="180" speed="14.48" />
        <yweather:atmosphere humidity="53" visibility="2.61" pressure="1006.1" rising="0" />
        <yweather:astronomy sunrise="4:51 am" sunset="7:32 pm"/>
        <item>
            <geo:lat>39.91</geo:lat>
            <geo:long>116.39</geo:long>
            <pubDate>Wed, 27 May 2015 11:00 am CST</pubDate>
            <yweather:condition text="Haze" code="21" temp="28" date="Wed, 27 May 2015 11:00 am CST" />
            <yweather:forecast day="Wed" date="27 May 2015" low="20" high="33" text="Partly Cloudy" code="30" />
            <yweather:forecast day="Thu" date="28 May 2015" low="21" high="34" text="Sunny" code="32" />
            <yweather:forecast day="Fri" date="29 May 2015" low="18" high="25" text="AM Showers" code="39" />
            <yweather:forecast day="Sat" date="30 May 2015" low="18" high="32" text="Sunny" code="32" />
            <yweather:forecast day="Sun" date="31 May 2015" low="20" high="37" text="Sunny" code="32" />
        </item>
    </channel>
</rss>
'''
# 例項化類
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}}

希望能夠幫助到大家,有什麼問題可以 直接評論即可,如果不夠詳細的話也可以說,我會及時回覆的。

相關文章