更簡單高效的HTML數據提取-Xpath


XPath 是一門在 XML 文檔中查找信息的語言。XPath 用於在 XML 文檔中通過元素和屬性進行導航。

相比於BeautifulSoupXpath在提取數據時會更加的方便。


安裝

在Python中很多庫都有提供Xpath的功能,但是最基本的還是lxml這個庫,效率最高。在之前BeautifulSoup章節中我們也介紹到了lxml是如何安裝的。

pip install lxml

語法

XPath 使用路徑表達式在 XML 文檔中選取節點。節點是通過沿着路徑或者 step 來選取的。

我們將用以下的HTML文檔來進行演示:

html_doc = '''<html>
​
<head></head>
​
<body>
    <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">
            <title lang="en">Learning XML</title>
            <author>Erik T. Ray</author>
            <year>2003</year>            <price>39.95</price>        </book>​    </bookstore></body>​</html>'''


from lxml import etree
​
page = etree.HTML(html_doc)

 

 


路徑查找

表達式 描述
nodename 選取此節點的子節點。
/ 從當前根節點選取。
// 從匹配選擇的當前節點選擇文檔中的節點,而不考慮它們的位置。
. 選取當前節點。
.. 選取當前節點的父節點。
@ 選取屬性。
  • 查找當前節點的子節點

    In [1]: page.xpath('head')
    Out[1]: [<Element head at 0x111c74c48>]

     

  • 從根節點進行查找

    In [2]: page.xpath('/html')
    Out[2]: [<Element html at 0x11208be88>]

     

  • 從整個文檔中所有節點查找

    In [3]: page.xpath('//book')
    Out[3]:
    [<Element book at 0x1128c02c8>,
     <Element book at 0x111c74108>,
     <Element book at 0x111fd2288>,
     <Element book at 0x1128da348>]

     

  • 選取當前節點的父節點

    In [4]: page.xpath('//book')[0].xpath('..')
    Out[4]: [<Element bookstore at 0x1128c0ac8>]

     

  • 選取屬性

    In [5]: page.xpath('//book')[0].xpath('@category')
    Out[5]: ['COOKING']

     


節點查找

表達式 結果
nodename[1] 選取第一個元素。
nodename[last()] 選取最后一個元素。
nodename[last()-1] 選取倒數第二個元素。
nodename[position()<3] 選取前兩個子元素。
nodename[@lang] 選取擁有名為 lang 的屬性的元素。
nodename[@lang='eng'] 選取擁有lang屬性,且值為 eng 的元素。
  • 選取第二個book元素

    In [1]: page.xpath('//book[2]/@category')
    Out[1]: ['CHILDREN']

     

  • 選取倒數第三個book元素

    In [2]: page.xpath('//book[last()-2]/@category')
    Out[2]: ['CHILDREN']
  • 選取第二個元素開始的所有元素

    In [3]: page.xpath('//book[position() > 1]/@category')
    Out[3]: ['CHILDREN', 'WEB', 'WEB']

     

  • 選取category屬性為WEB的的元素

    In [4]: page.xpath('//book[@category="WEB"]/@category')
    Out[4]: ['WEB', 'WEB']

     


未知節點

通配符 描述
* 匹配任何元素節點。
@* 匹配任何屬性節點。
  • 匹配第一個book元素下的所有元素

    In [1]: page.xpath('//book[1]/*')
    Out[1]:
    [<Element title at 0x111f76788>,
     <Element author at 0x111f76188>,
     <Element year at 0x1128c1a88>,
     <Element price at 0x1128c1cc8>]

     


獲取節點中的文本

  • text()獲取某個節點下的文本

    In [1]: page.xpath('//book[1]/author/text()')
    Out[1]: ['Giada De Laurentiis']

     

    如果這個節點下有多個文本,則只能取到一段。

  • string()獲取某個節點下所有的文本

    In [2]: page.xpath('string(//book[1])')
    Out[2]: '\n            Everyday Italian\n            Giada De Laurentiis\n            2005\n            30.00\n        '

     


選取多個路徑

通過在路徑表達式中使用“|”運算符,您可以選取若干個路徑。

In [1]: page.xpath('//book[1]/title/text() | //book[1]/author/text()')
Out[1]: ['Everyday Italian', 'Giada De Laurentiis']

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM