日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

XPath和lxml类库

發(fā)布時(shí)間:2024/7/5 编程问答 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 XPath和lxml类库 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

XPath,我們可以先將 HTML文件 轉(zhuǎn)換成 XML文檔,然后用 XPath 查找 HTML 節(jié)點(diǎn)或元素。

什么是XML

  • XML 指可擴(kuò)展標(biāo)記語言(EXtensible Markup Language)
  • XML 是一種標(biāo)記語言,很類似 HTML
  • XML 的設(shè)計(jì)宗旨是傳輸數(shù)據(jù),而非顯示數(shù)據(jù)
  • XML 的標(biāo)簽需要我們自行定義。
  • XML 被設(shè)計(jì)為具有自我描述性。
  • XML 是 W3C 的推薦標(biāo)準(zhǔn)

W3School官方文檔:http://www.w3school.com.cn/xml/index.asp

XML 和 HTML 的區(qū)別

數(shù)據(jù)格式描述設(shè)計(jì)目標(biāo)
XMLExtensible Markup Language?(可擴(kuò)展標(biāo)記語言)被設(shè)計(jì)為傳輸和存儲(chǔ)數(shù)據(jù),其焦點(diǎn)是數(shù)據(jù)的內(nèi)容。
HTMLHyperText Markup Language?(超文本標(biāo)記語言)顯示數(shù)據(jù)以及如何更好顯示數(shù)據(jù)。
HTML DOMDocument Object Model for HTML?(文檔對(duì)象模型)通過 HTML DOM,可以訪問所有的 HTML 元素,連同它們所包含的文本和屬性。可以對(duì)其中的內(nèi)容進(jìn)行修改和刪除,同時(shí)也可以創(chuàng)建新的元素。
XML文檔示例
<?xml version="1.0" encoding="utf-8"?><bookstore> <book category="cooking"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="children"> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="web"> <title lang="en">XQuery Kick Start</title> <author>James McGovern</author> <author>Per Bothner</author> <author>Kurt Cagle</author> <author>James Linn</author> <author>Vaidyanathan Nagarajan</author> <year>2003</year> <price>49.99</price> </book> <book category="web" cover="paperback"> <title lang="en">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book> </bookstore>
HTML DOM 模型示例

HTML DOM 定義了訪問和操作 HTML 文檔的標(biāo)準(zhǔn)方法,以樹結(jié)構(gòu)方式表達(dá) HTML 文檔。


XML的節(jié)點(diǎn)關(guān)系

1. 父(Parent)

每個(gè)元素以及屬性都有一個(gè)父。

下面是一個(gè)簡(jiǎn)單的XML例子中,book 元素是 title、author、year 以及 price 元素的父:

<?xml version="1.0" encoding="utf-8"?><book><title>Harry Potter</title><author>J K. Rowling</author><year>2005</year><price>29.99</price> </book>

2. 子(Children)

元素節(jié)點(diǎn)可有零個(gè)、一個(gè)或多個(gè)子。

在下面的例子中,title、author、year 以及 price 元素都是 book 元素的子:

<?xml version="1.0" encoding="utf-8"?><book><title>Harry Potter</title><author>J K. Rowling</author><year>2005</year><price>29.99</price> </book>

3. 同胞(Sibling)

擁有相同的父的節(jié)點(diǎn)

在下面的例子中,title、author、year 以及 price 元素都是同胞:

<?xml version="1.0" encoding="utf-8"?><book><title>Harry Potter</title><author>J K. Rowling</author><year>2005</year><price>29.99</price> </book>

4. 先輩(Ancestor)

某節(jié)點(diǎn)的父、父的父,等等。

在下面的例子中,title 元素的先輩是 book 元素和 bookstore 元素:

<?xml version="1.0" encoding="utf-8"?><bookstore><book><title>Harry Potter</title><author>J K. Rowling</author><year>2005</year><price>29.99</price> </book></bookstore>

5. 后代(Descendant)

某個(gè)節(jié)點(diǎn)的子,子的子,等等。

在下面的例子中,bookstore 的后代是 book、title、author、year 以及 price 元素:

<?xml version="1.0" encoding="utf-8"?><bookstore><book><title>Harry Potter</title><author>J K. Rowling</author><year>2005</year><price>29.99</price> </book></bookstore>

什么是XPath?

XPath (XML Path Language) 是一門在 XML 文檔中查找信息的語言,可用來在 XML 文檔中對(duì)元素和屬性進(jìn)行遍歷。

W3School官方文檔:http://www.w3school.com.cn/xpath/index.asp

XPath 開發(fā)工具

  • 開源的XPath表達(dá)式編輯工具:XMLQuire(XML格式文件可用)
  • Chrome插件 XPath Helper
  • Firefox插件 XPath Checker
  • 選取節(jié)點(diǎn)

    XPath 使用路徑表達(dá)式來選取 XML 文檔中的節(jié)點(diǎn)或者節(jié)點(diǎn)集。這些路徑表達(dá)式和我們?cè)诔R?guī)的電腦文件系統(tǒng)中看到的表達(dá)式非常相似。

    下面列出了最常用的路徑表達(dá)式:

    表達(dá)式描述
    nodename選取此節(jié)點(diǎn)的所有子節(jié)點(diǎn)。
    /從根節(jié)點(diǎn)選取。
    //從匹配選擇的當(dāng)前節(jié)點(diǎn)選擇文檔中的節(jié)點(diǎn),而不考慮它們的位置。
    .選取當(dāng)前節(jié)點(diǎn)。
    ..選取當(dāng)前節(jié)點(diǎn)的父節(jié)點(diǎn)。
    @選取屬性。

    在下面的表格中,我們已列出了一些路徑表達(dá)式以及表達(dá)式的結(jié)果:

    ?路徑表達(dá)式結(jié)果
    bookstore選取 bookstore 元素的所有子節(jié)點(diǎn)。
    /bookstore選取根元素 bookstore。注釋:假如路徑起始于正斜杠( / ),則此路徑始終代表到某元素的絕對(duì)路徑!
    bookstore/book選取屬于 bookstore 的子元素的所有 book 元素。
    //book選取所有 book 子元素,而不管它們?cè)谖臋n中的位置。
    bookstore//book選擇屬于 bookstore 元素的后代的所有 book 元素,而不管它們位于 bookstore 之下的什么位置。
    //@lang選取名為 lang 的所有屬性。

    謂語(Predicates)

    謂語用來查找某個(gè)特定的節(jié)點(diǎn)或者包含某個(gè)指定的值的節(jié)點(diǎn),被嵌在方括號(hào)中。

    在下面的表格中,我們列出了帶有謂語的一些路徑表達(dá)式,以及表達(dá)式的結(jié)果:

    路徑表達(dá)式結(jié)果
    /bookstore/book[1]選取屬于 bookstore 子元素的第一個(gè) book 元素。
    /bookstore/book[last()]選取屬于 bookstore 子元素的最后一個(gè) book 元素。
    /bookstore/book[last()-1]選取屬于 bookstore 子元素的倒數(shù)第二個(gè) book 元素。
    /bookstore/book[position()<3]選取最前面的兩個(gè)屬于 bookstore 元素的子元素的 book 元素。
    //title[@lang]選取所有擁有名為 lang 的屬性的 title 元素。
    //title[@lang=’eng’]選取所有 title 元素,且這些元素?fù)碛兄禐?eng 的 lang 屬性。
    /bookstore/book[price>35.00]選取 bookstore 元素的所有 book 元素,且其中的 price 元素的值須大于 35.00。
    /bookstore/book[price>35.00]/title選取 bookstore 元素中的 book 元素的所有 title 元素,且其中的 price 元素的值須大于 35.00。

    選取未知節(jié)點(diǎn)

    XPath 通配符可用來選取未知的 XML 元素。

    通配符描述
    *匹配任何元素節(jié)點(diǎn)。
    @*匹配任何屬性節(jié)點(diǎn)。
    node()匹配任何類型的節(jié)點(diǎn)。

    在下面的表格中,我們列出了一些路徑表達(dá)式,以及這些表達(dá)式的結(jié)果:

    路徑表達(dá)式結(jié)果
    /bookstore/*選取 bookstore 元素的所有子元素。
    //*選取文檔中的所有元素。
    //title[@*]選取所有帶有屬性的 title 元素。

    選取若干路徑

    通過在路徑表達(dá)式中使用“|”運(yùn)算符,您可以選取若干個(gè)路徑。

    實(shí)例

    在下面的表格中,我們列出了一些路徑表達(dá)式,以及這些表達(dá)式的結(jié)果:

    路徑表達(dá)式結(jié)果
    //book/title | //book/price選取 book 元素的所有 title 和 price 元素。
    //title | //price選取文檔中的所有 title 和 price 元素。
    /bookstore/book/title | //price選取屬于 bookstore 元素的 book 元素的所有 title 元素,以及文檔中所有的 price 元素。

    XPath的運(yùn)算符

    下面列出了可用在 XPath 表達(dá)式中的運(yùn)算符:

    這些就是XPath的語法內(nèi)容,在運(yùn)用到Python抓取時(shí)要先轉(zhuǎn)換為xml。

    lxml庫

    lxml 是 一個(gè)HTML/XML的解析器,主要的功能是如何解析和提取 HTML/XML 數(shù)據(jù)。

    lxml和正則一樣,也是用 C 實(shí)現(xiàn)的,是一款高性能的 Python HTML/XML 解析器,我們可以利用之前學(xué)習(xí)的XPath語法,來快速的定位特定元素以及節(jié)點(diǎn)信息。

    lxml python 官方文檔:http://lxml.de/index.html

    需要安裝C語言庫,可使用 pip 安裝:pip install lxml?(或通過wheel方式安裝)

    初步使用

    我們利用它來解析 HTML 代碼,簡(jiǎn)單示例:

    # lxml_test.py# 使用 lxml 的 etree 庫 from lxml import etree text = ''' <div><ul><li class="item-0"><a href="link1.html">first item</a></li><li class="item-1"><a href="link2.html">second item</a></li><li class="item-inactive"><a href="link3.html">third item</a></li><li class="item-1"><a href="link4.html">fourth item</a></li><li class="item-0"><a href="link5.html">fifth item</a> # 注意,此處缺少一個(gè) </li> 閉合標(biāo)簽</ul></div> '''#利用etree.HTML,將字符串解析為HTML文檔 html = etree.HTML(text) # 按字符串序列化HTML文檔 result = etree.tostring(html) print(result)

    輸出結(jié)果:

    <html><body> <div><ul><li class="item-0"><a href="link1.html">first item</a></li><li class="item-1"><a href="link2.html">second item</a></li><li class="item-inactive"><a href="link3.html">third item</a></li><li class="item-1"><a href="link4.html">fourth item</a></li><li class="item-0"><a href="link5.html">fifth item</a></li> </ul></div> </body></html>

    lxml 可以自動(dòng)修正 html 代碼,例子里不僅補(bǔ)全了 li 標(biāo)簽,還添加了 body,html 標(biāo)簽。

    文件讀取:

    除了直接讀取字符串,lxml還支持從文件里讀取內(nèi)容。我們新建一個(gè)hello.html文件:

    <!-- hello.html --><div><ul><li class="item-0"><a href="link1.html">first item</a></li><li class="item-1"><a href="link2.html">second item</a></li><li class="item-inactive"><a href="link3.html"><span class="bold">third item</span></a></li><li class="item-1"><a href="link4.html">fourth item</a></li><li class="item-0"><a href="link5.html">fifth item</a></li></ul></div>

    再利用 etree.parse() 方法來讀取文件。

    # lxml_parse.pyfrom lxml import etree# 讀取外部文件 hello.html html = etree.parse('./hello.html') result = etree.tostring(html, pretty_print=True)print(result)

    輸出結(jié)果與之前相同:

    <html><body> <div><ul><li class="item-0"><a href="link1.html">first item</a></li><li class="item-1"><a href="link2.html">second item</a></li><li class="item-inactive"><a href="link3.html">third item</a></li><li class="item-1"><a href="link4.html">fourth item</a></li><li class="item-0"><a href="link5.html">fifth item</a></li> </ul></div> </body></html>

    XPath實(shí)例測(cè)試

    1. 獲取所有的?<li>?標(biāo)簽

    # xpath_li.pyfrom lxml import etreehtml = etree.parse('hello.html') print type(html) # 顯示etree.parse() 返回類型result = html.xpath('//li')print result # 打印<li>標(biāo)簽的元素集合 print len(result) print type(result) print type(result[0])

    輸出結(jié)果:

    <type 'lxml.etree._ElementTree'> [<Element li at 0x1014e0e18>, <Element li at 0x1014e0ef0>, <Element li at 0x1014e0f38>, <Element li at 0x1014e0f80>, <Element li at 0x1014e0fc8>] 5 <type 'list'> <type 'lxml.etree._Element'>

    2. 繼續(xù)獲取<li>?標(biāo)簽的所有?class屬性

    # xpath_li.pyfrom lxml import etreehtml = etree.parse('hello.html') result = html.xpath('//li/@class')print result

    運(yùn)行結(jié)果

    ['item-0', 'item-1', 'item-inactive', 'item-1', 'item-0']

    3. 繼續(xù)獲取<li>標(biāo)簽下hre?為?link1.html?的?<a>?標(biāo)簽

    # xpath_li.pyfrom lxml import etreehtml = etree.parse('hello.html') result = html.xpath('//li/a[@href="link1.html"]')print result

    運(yùn)行結(jié)果

    [<Element a at 0x10ffaae18>]

    4. 獲取<li>?標(biāo)簽下的所有?<span>?標(biāo)簽

    # xpath_li.pyfrom lxml import etreehtml = etree.parse('hello.html')#result = html.xpath('//li/span') #注意這么寫是不對(duì)的: #因?yàn)?/ 是用來獲取子元素的,而 <span> 并不是 <li> 的子元素,所以,要用雙斜杠result = html.xpath('//li//span')print result

    運(yùn)行結(jié)果

    [<Element span at 0x10d698e18>]

    5. 獲取?<li>?標(biāo)簽下的<a>標(biāo)簽里的所有 class

    # xpath_li.pyfrom lxml import etreehtml = etree.parse('hello.html') result = html.xpath('//li/a//@class')print result

    運(yùn)行結(jié)果

    ['blod']

    6. 獲取最后一個(gè)?<li>?的?<a>?的 href

    # xpath_li.pyfrom lxml import etreehtml = etree.parse('hello.html')result = html.xpath('//li[last()]/a/@href') # 謂語 [last()] 可以找到最后一個(gè)元素print result

    運(yùn)行結(jié)果

    ['link5.html']

    7. 獲取倒數(shù)第二個(gè)元素的內(nèi)容

    # xpath_li.pyfrom lxml import etreehtml = etree.parse('hello.html') result = html.xpath('//li[last()-1]/a')# text 方法可以獲取元素內(nèi)容 print result[0].text

    運(yùn)行結(jié)果

    fourth item

    8. 獲取?class?值為?bold?的標(biāo)簽名

    # xpath_li.pyfrom lxml import etreehtml = etree.parse('hello.html')result = html.xpath('//*[@class="bold"]')# tag方法可以獲取標(biāo)簽名 print result[0].tag

    運(yùn)行結(jié)果

    span

    總結(jié)

    以上是生活随笔為你收集整理的XPath和lxml类库的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。