python使用ElementTree解析XML檔案

來源:互聯網
上載者:User

標籤: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檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.