爬蟲-使用lxml解析html資料

Wang發表於2021-01-20

使用lxml之前,我們首先要會使用XPath。利用XPath,就可以將html文件當做xml文件去進行處理解析了。

一、XPath的簡單使用:

XPath (XML Path Language) 是一門在 XML 文件中查詢資訊的語言,可用來在 XML 文件中對元素和屬性進行遍歷。

1.開發工具的安裝

Chrome瀏覽器,可以安裝Xpath Helper外掛。如果從網上下載外掛,得到的檔案以.crx結尾,不能直接新增到瀏覽器擴充套件程式裡,我們需要將這個檔案改為.zip結尾,然後新建一個資料夾,將.zip檔案解壓到新建的資料夾內。通過瀏覽器的擴充套件程式-載入已解壓的擴充套件程式-選擇該資料夾就可以安裝好外掛了。

2.語法

XPath使用路徑表示式來選取XML文件中的節點或者節點集。節點是通過沿著路徑(path)或步(steps)來選取的。這些路徑表示式和我們在常規的電腦檔案系統中看到的表示式非常相似。

  • XML例項文件

    <?xml version="1.0" encoding="ISO-8859-1"?>
    
    <bookstore>
    
    <book>
      <title lang="eng">Harry Potter</title>
      <price>29.99</price>
    </book>
    
    <book>
      <title lang="eng">Learning XML</title>
      <price>39.95</price>
    </book>
    
    </bookstore>

    下面的例子中都使用這個文件進行演示。

  • 選取節點

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

常見路徑表示式:

表示式 描述
節點名 必須是根節點,選取此節點的所有子節點。
/ 從根節點選取。
// 從匹配選擇的當前節點選擇文件中的節點,而不考慮它們的位置。
. 選取當前節點。
.. 選取當前節點的父節點。
@ 選取屬性。

示例:

路徑表示式 結果
bookstore 選取 bookstore 元素的所有子節點。
/bookstore

選取根元素 bookstore。

註釋:假如路徑起始於正斜槓( / ),則此路徑始終代表到某元素的絕對路徑!

bookstore/book 選取屬於 bookstore 的子元素的所有 book 元素。
//book 選取所有 book 子元素,而不管它們在文件中的位置。
bookstore//book 選擇屬於 bookstore 元素的後代的所有 book 元素,而不管它們位於 bookstore 之下的什麼位置。
//@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] 選取所有擁有名為 lang 的屬性的 title 元素。
//title[@lang='eng'] 選取所有 title 元素,且這些元素擁有值為 eng 的 lang 屬性。
/bookstore/book[price>35.00] 選取 bookstore 元素的所有 book 元素,且其中的 price 元素的值須大於 35.00。
/bookstore/book[price>35.00]/title 選取 bookstore 元素中的 book 元素的所有 title 元素,且其中的 price 元素的值須大於 35.00。

 

  • 選取未知節點和屬性

XPath 萬用字元可用來選取未知的 XML 元素和屬性。

萬用字元:

萬用字元 描述
* 匹配任何節點。
@* 匹配任何屬性

示例:

路徑表示式 結果
/bookstore/* 選取 bookstore 元素的所有子元素。
//* 選取文件中的所有元素。
//title[@*] 選取所有帶有屬性的 title 元素。
  • 選取若干路徑

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

示例:

路徑表示式 結果
//book/title | //book/price 選取 book 元素的所有 title 和 price 元素。
//title | //price 選取文件中的所有 title 和 price 元素。
/bookstore/book/title | //price 選取屬於 bookstore 元素的 book 元素的所有 title 元素,以及文件中所有的 price 元素。

3.運算子

下面列出了可用在 XPath 表示式中的運算子:

                 

二、lxml庫

 lxml 是 一個HTML/XML的解析器,主要的功能是如何解析和提取 HTML/XML 資料。

 lxml和正則一樣,也是用C實現的,是一款高效能的 Python HTML/XML 解析器,我們可以利用XPath語法,來快速的定位特定元素以及節點資訊。

1.安裝

  • 需要安裝C語言庫,可使用 pip 安裝
    sudo pip3 install lxml

 

 

2.簡單使用(僅列出常見的一些操作)

 

  • etree

    • 解析html資料,主要就是用到lxml庫中的etree
  • etree.HTML()

    • 引數為字串,讀取字串,返回html元素,並且會自動修正html程式碼,比如缺少html標籤和body標籤,則會自動添上
  • etree.parse()

    • 引數為檔名,從檔案讀取內容,返回_ElementTree
  • etree.tostring()

    • 引數為元素或者元素樹,序列化成位元組型別
  • Element.xpath()或者_ElementTree.xpath()

    • 引數是xpath表示式字串,返回的是列表。如果表示式選取的是元素,則列表由元素組成,如果表示式選取的是屬性,則列表由屬性的值組成
  • Element.tag

    • 元素tag屬性,返回元素標籤名
  • Element.text

    • 元素text屬性,返回元素內容
  • 示例:

    In [1]: from lxml import etree #匯入etree
    
    In [2]: 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"><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>
       ...: '''
    
    In [3]: html = etree.HTML(text) #讀取字串
    
    In [4]: html #返回html元素
    Out[4]: <Element html at 0x7f3ad0bb8340>
    
    In [5]: etree.tostring(html)#序列化成位元組型別,並自動添上了html標籤和body標籤
    Out[5]: b'<html><body><div>\n    <ul>\n        <li class="item-0"><a href="link1.html">first item</a></li>\n        <li class="item-1"><a href="link2.html">second item</a></li>\n        <li class="item-inactive"><a href="link3.html"><span class="bold">third item</span></a></li>\n        <li class="item-1"><a href="link4.html">fourth item</a></li>\n        <li class="item-0"><a href="link5.html">fifth item</a></li>\n    </ul>\n</div>\n</body></html>'
    
    In [6]: html2 = etree.parse('./test.html')#從檔案讀取
    
    In [7]: html2 #返回元素樹
    Out[7]: <lxml.etree._ElementTree at 0x7fc54d818d00>
    
    In [8]: etree.tostring(html2)
    Out[8]: b'<body>\n    <div>\n        <ul>\n             <li class="item-0"><a href="link1.html">first item</a></li>\n             <li class="item-1"><a href="link2.html">second item</a></li>\n             <li class="item-inactive"><a href="link3.html"><span class="bold">third item</span></a></li>\n             <li class="item-1"><a href="link4.html">fourth item</a></li>\n             <li class="item-0"><a href="link5.html">fifth item</a></li>\n         </ul>\n     </div>\n</body>'
    
    In [9]: element_list = html.xpath('//a')#呼叫元素的xpath方法,選取文件中的所有a元素
    
    In [10]: element_list #返回所有a元素組成的列表
    Out[10]: 
    [<Element a at 0x7fc54d849ec0>,
     <Element a at 0x7fc54d91b080>,
     <Element a at 0x7fc54d86fc80>,
     <Element a at 0x7fc54d878e40>,
     <Element a at 0x7fc54d878040>]
    
    In [11]: element_list[0].tag #元素tag屬性,返回標籤名
    Out[11]: 'a'
    
    In [12]: element_list[0].text #元素text屬性,返回元素內容
    Out[12]: 'first item'
    
    In [13]: attr_value_list = html.xpath('//a/@href') #呼叫元素的xpath方法,選取文件中所有a元素的href屬性
    
    In [14]: attr_value_list #返回href屬性值組成的列表
    Out[14]: ['link1.html', 'link2.html', 'link3.html', 'link4.html', 'link5.html']

     

相關文章