Python爬蟲之xlml解析庫(全面瞭解),pythonxlml

來源:互聯網
上載者:User

Python爬蟲之xlml解析庫(全面瞭解),pythonxlml

1.Xpath

Xpath是一門在XML中尋找資訊的語言,可用來在XML文檔中對元素和屬性進行遍曆。XQuery和xpoint都是構建於xpath表達之上

2.節點

父(parent),子(children),兄弟(sibling),先輩(ancetstor),後代(Decendant)

3.選取節點

路徑運算式

運算式 描述 路徑運算式 結果
nodename 選取此節點上的所有的子節點 bookstore 選取bookstore元素的所有子節點
/ 從根節點上選取 /bookstore 選取根項目bookstore,為絕對路徑
// 從匹配選擇的當前節點選擇文檔中的節點,不考慮位置 //book 選取所有的book子項目,而不管他們在文檔的位置
. 選取當前節點 bookstore//book 選擇bookstore後代中所有的book元素
.. 選取當前節點的父節點
@ 選取屬性 //@lang 選取名為lang的所有屬性

謂語

  謂語用來尋找某個特定的節點或者包含某個指定的值的節點

  謂語被嵌在方括弧中

路徑運算式 結果
/bookstore/book[1] 選取屬於bookstore子項目的第一個book元素
/bookstore/book[last()] 選取屬於bookstore子項目的最後book元素
/bookstore/book[last()-1] 選取屬於bookstore子項目的倒數第二個book元素
/bookstore/book[position()<3] 選取最前面的兩個屬於bookstore元素的子項目的book元素
//title[@lang='eng'] 選取所有的title元素,並且這些元素擁有值為eng的lang屬性
/bookstore/book[price>35.0] 選取bookstore元素的所有book元素,且其中的price值大於35.0

選取未知節點(萬用字元)

*  匹配任何 元素節點

@*  匹配任何屬性節點

node()  匹配任何類型的節點

4.lxml用法

#!/usr/bin/python#_*_coding:utf-8_*_from lxml import etreetext='''<div> <ul>  <li class="item-0"><a href="link1.html" rel="external nofollow" rel="external nofollow" >first item</a></li>  <li class="item-1"><a href="link2.html" rel="external nofollow" >second item</a></li>  <li class="item-inactive"><a href="link3.html" rel="external nofollow" >third item</a></li>  <li class="item-1"><a href="link4.html" rel="external nofollow" >fourth item</a></li>  <li class="item-0"><a href="link5.html" rel="external nofollow" >fifth item</a> </ul></div>  '''# html=etree.HTML(text) #html對象,儲存在地址中,有自動修正功能# result=etree.tostring(html) #將html對象轉化為字串html=etree.parse('hello.html')# result=etree.tostring(html,pretty_print=True)# print resultprint type(html)result= html.xpath('//li')print resultprint len(result)print type(result)print type(result[0])print html.xpath('//li/@class') # 擷取li標籤下的所有的classprint html.xpath('//li/a[@href="link1.html" rel="external nofollow" rel="external nofollow" ]') #擷取li標籤下href為link1的<a>標籤print html.xpath('//li//span') #擷取li標籤下所有的span標籤print html.xpath('//li[last()-1]/a')[0].text #擷取倒數第二個元素的內容

以上這篇Python爬蟲之xlml解析庫(全面瞭解)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.