標籤:color 名稱 rom span write str 利用 get 實現
一、將XML網頁儲存到本地
要載入XML檔案首先應該將網頁上的資訊提取出來,儲存為本地XML檔案。抓取網頁資訊可以python的urllib模組。
代碼如下:
from urllib import urlopenurl = "http://********/**"resp = urlopen(url).read()f = open(‘檔案儲存路徑‘, ‘w‘)f.write(resp)f.close()
二、解析XML檔案
python有許多可以用來解析XML檔案的函數,在這裡介紹ElementTree(簡稱ET).它提供輕量級的python式API。實現邏輯簡單,解析效率高。利用ET解析XML檔案的方法是:先找出父級標籤,然後再一級一級迴圈找出所需要的子標籤,代碼如下:
import xml.etree.cElementTree as ETtree = ET.parse("***.xml") #載入xml檔案root = tree.getroot() #得到第二級標籤for child_of_root in root[1]:#root[1]為第二級標籤中的第二個子標籤 for child1 in child_of_root[7]: #原理同上 for child2 in child1: print child2.tag, child2.attrib, child2.text for child3 in child_of_root[8]: for child4 in child3: print child4.tag, child4.attrib, child4.text
在上述代碼中,child_of_root[7]表示在該級標籤中的第八個子標籤,在for child2 in child1中是遍曆child1的所有子標籤,列印出子標籤的名稱、屬性、文本。這樣就可以將XML檔案解析完成,得到我們所想要的資訊。
python使用ElementTree解析XML檔案