XPath與lxml類庫

我正則用的很差,處理HTML文檔很累,有沒有其餘的方法?html

有!那就是XPath,咱們能夠先將 HTML文件 轉換成 XML文檔,而後用 XPath 查找 HTML 節點或元素。python

什麼是XML

  • XML 指可擴展標記語言(EXtensible Markup Language)
  • XML 是一種標記語言,很相似 HTML
  • XML 的設計宗旨是傳輸數據,而非顯示數據
  • XML 的標籤須要咱們自行定義。
  • XML 被設計爲具備自我描述性。
  • XML 是 W3C 的推薦標準

W3School官方文檔:http://www.w3school.com.cn/xm...web

XML 和 HTML 的區別

圖片描述

<?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 文檔的標準方法,以樹結構方式表達 HTML 文檔。
圖片描述工具

XML的節點關係

1. 父(Parent)

每一個元素以及屬性都有一個父。性能

下面是一個簡單的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)

元素節點可有零個、一個或多個子。開發工具

在下面的例子中,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)

擁有相同的父的節點ui

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

<?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)

某節點的父、父的父,等等。

在下面的例子中,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)

某個節點的子,子的子,等等。

在下面的例子中,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 文檔中對元素和屬性進行遍歷。

W3School官方文檔:http://www.w3school.com.cn/xp...

XPath 開發工具

  1. 開源的XPath表達式編輯工具:XMLQuire(XML格式文件可用)
  2. Chrome插件 XPath Helper
  3. Firefox插件 XPath Checker

選取節點

XPath 使用路徑表達式來選取 XML 文檔中的節點或者節點集。這些路徑表達式和咱們在常規的電腦文件系統中看到的表達式很是類似。

下面列出了最經常使用的路徑表達式:
圖片描述

在下面的表格中,咱們已列出了一些路徑表達式以及表達式的結果:

圖片描述

謂語(Predicates)

謂語用來查找某個特定的節點或者包含某個指定的值的節點,被嵌在方括號中。

在下面的表格中,咱們列出了帶有謂語的一些路徑表達式,以及表達式的結果:

圖片描述
選取未知節點

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

圖片描述
在下面的表格中,咱們列出了一些路徑表達式,以及這些表達式的結果:

圖片描述

選取若干路徑

經過在路徑表達式中使用「|」運算符,您能夠選取若干個路徑。

實例

在下面的表格中,咱們列出了一些路徑表達式,以及這些表達式的結果:

XPath的運算符

下面列出了可用在 XPath 表達式中的運算符:
圖片描述

這些就是XPath的語法內容,在運用到Python抓取時要先轉換爲xml。

lxml庫

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

lxml和正則同樣,也是用 C 實現的,是一款高性能的 Python HTML/XML 解析器,咱們能夠利用以前學習的XPath語法,來快速的定位特定元素以及節點信息。

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

須要安裝C語言庫,可以使用 pip 安裝:pip install lxml (或經過wheel方式安裝)

初步使用

咱們利用它來解析 HTML 代碼,簡單示例:

# 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> # 注意,此處缺乏一個 </li> 閉合標籤
     </ul>
 </div>
'''

#利用etree.HTML,將字符串解析爲HTML文檔
html = etree.HTML(text) 

# 按字符串序列化HTML文檔
result = etree.tostring(html) 

print(result)

輸出結果:

<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 能夠自動修正 html 代碼,例子裏不只補全了 li 標籤,還添加了 body,html 標籤。

文件讀取:

除了直接讀取字符串,lxml還支持從文件裏讀取內容。咱們新建一個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.py

from lxml import etree

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

print(result)

輸出結果與以前相同:

<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實例測試

1. 獲取全部的 <li> 標籤

# xpath_li.py

from lxml import etree

html = etree.parse('hello.html')
print type(html)  # 顯示etree.parse() 返回類型

result = html.xpath('//li')

print result  # 打印<li>標籤的元素集合
print len(result)
print type(result)
print type(result[0])

輸出結果:

<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. 繼續獲取<li> 標籤的全部 class屬性

# xpath_li.py

from lxml import etree

html = etree.parse('hello.html')
result = html.xpath('//li/@class')

print result

運行結果

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

3. 繼續獲取<li>標籤下hre 爲 link1.html 的 【a】(此處爲英文狀態下的中括號 爲了防止Markdown語法轉義 因此寫成中文狀態下的中括號) 標籤

# xpath_li.py

from lxml import etree

html = etree.parse('hello.html')
result = html.xpath('//li/a[@href="link1.html"]')

print result

運行結果

[<Element a at 0x10ffaae18>]

4. 獲取<li> 標籤下的全部 <span> 標籤

# xpath_li.py

from lxml import etree

html = etree.parse('hello.html')

#result = html.xpath('//li/span')
#注意這麼寫是不對的:
#由於 / 是用來獲取子元素的,而 <span> 並非 <li> 的子元素,因此,要用雙斜槓

result = html.xpath('//li//span')

print result

運行結果

[<Element span at 0x10d698e18>]

5. 獲取 <li> 標籤下的標籤裏的全部 class

# xpath_li.py

from lxml import etree

html = etree.parse('hello.html')
result = html.xpath('//li/a//@class')

print result

運行結果

['blod']

6. 獲取最後一個 <li> 的 的 href

# xpath_li.py

from lxml import etree

html = etree.parse('hello.html')

result = html.xpath('//li[last()]/a/@href')
# 謂語 [last()] 能夠找到最後一個元素

print result
運行結果

['link5.html']

7. 獲取倒數第二個元素的內容

# xpath_li.py

from lxml import etree

html = etree.parse('hello.html')
result = html.xpath('//li[last()-1]/a')

# text 方法能夠獲取元素內容
print result[0].text

運行結果

fourth item

8. 獲取 class 值爲 bold 的標籤名

# xpath_li.py

from lxml import etree

html = etree.parse('hello.html')

result = html.xpath('//*[@class="bold"]')

# tag方法能夠獲取標籤名
print result[0].tag

運行結果

span
相關文章
相關標籤/搜索