python筆記 常用內建模組 xml(習題)

2021-08-21 12:55:11 字數 1450 閱讀 4749

請利用sax編寫程式解析yahoo的xml格式的天氣預報,獲取天氣預報:

引數woeid是城市**,要查詢某個城市**,可以在weather.yahoo.com搜尋城市,瀏覽器位址列的url就包含城市**。

**:

# -*- coding:utf-8 -*-

from xml.parsers.expat import parsercreate

from urllib import request

class defaultsaxhandler(object):

d=""

fore=

def start_element(self, name, attrs):

if name=="yweather:location" and "city" in attrs:

self.d=attrs['city']

elif name=="yweather:forecast":

self.fore[-1]["day"]=attrs['day']

self.fore[-1]["high"]=attrs['high']

self.fore[-1]["low"]=attrs['low']

# 測試:

url = ''

with request.urlopen(url, timeout=4) as f:

data = f.read()

handler = defaultsaxhandler()

parser = parsercreate()

parser.startelementhandler = handler.start_element

parser.parse(data.decode('utf-8'))

print("city:",handler.d)

for item in handler.fore:

print('---------------')

for k,v in item.items():

print("%s: %s" % (k,v))

執行:

明天要解決的問題:

1、感覺不熟悉的地方 tuple list 與dict區別,果然基礎沒打好,需要重新看一遍了

2、{},[ ],() 以及其操作,因為用了()出現

3、以及物件.變數呼叫類內部定義的變數,能否隔乙個函式進行傳值

4、對這個習題進行改良,可以輸出當天的天氣,將城市名稱,當天天氣,天氣預報都放在乙個裡面儲存

5、最後輸出%s,%s,%(k,v),與直接輸出的區別

Python常用內建模組

base64是一種用64個字元來表示任意二進位制資料的方法。用記事本開啟exe jpg pdf這些檔案時,我們都會看到一大堆亂碼,因為二進位制檔案包含很多無法顯示和列印的字元,所以,如果要讓記事本這樣的文字處理軟體能處理二進位制資料,就需要乙個二進位製到字串的轉換方法。base64是一種最常見的二進...

python淺學筆記12 常用內建模組

xmlhtmlparser 自稱足夠多,不需額外安裝其他模組。batteries included 獲取本地當前日期和時間 構造時間 timestamp 浮點數 0 1970.01.01 00 00 00 epoch time utc 時區時刻 timestamp 當前時刻 epoch time 的...

python常用內建模組(五)

requests 一 collections 是python內建的乙個集合模組,提供了許多有用的集合類。namedtuple,是乙個函式,用來建立乙個自定義的tuple物件,格式 namedtuple 名稱 屬性list 例如 建立乙個座標為 1,2 的點 from collections impo...