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>'''
1、路勁查找html
描述 | |
---|---|
nodename | 選取此節點的子節點。 |
/ | 從根節點選取。 |
// | 從匹配選擇的當前節點選擇文檔中的節點,而不考慮它們的位置。 |
. | 選取當前節點。 |
.. | 選取當前節點的父節點。 |
@ |
from lxml import etree page = etree.HTML(html_doc) page.xpath('/html') # 從跟節點查找 page.xpath('//book') # 從全部節點查找 page.xpath('//book')[0].xpath('..') # 選取當前節點的父節點 page.xpath('//book')[0].xpath('@category') # 選取屬性
node
表達式 | 結果 |
---|---|
nodename[1] | 選取第一個元素。 |
nodename[last()] | 選取最後一個元素。 |
nodename[last()-1] | 選取倒數第二個元素。 |
nodename[position()<3] | 選取前兩個子元素。 |
nodename[@lang] | 選取擁有名爲 lang 的屬性的元素。 |
nodename[@lang='eng'] |
page.xpath('//book[2]/@category') # 選取第二個book元素 page.xpath('//book[last()-2]/@category') # 選取倒數第三個book元素 page.xpath('//book[position() > 1]/@category') # 選取第二個元素開始的全部元素 page.xpath('//book[@category="WEB"]/@category') # 選取category屬性爲WEB的的元素
3、未知節點函數
描述 | |
---|---|
* | 匹配任何元素節點。 |
@* |
page.xpath('//book[1]/*') page.xpath('//book//title[@*="en"]')
4、xpath的運算符spa
運算符 | 描述 |
| | 計算兩個節點集 |
or | 或 |
and | 與 |
not | 非 |
page.xpath('//book[1]|//book[2]') # 同時獲取book1和book2的標籤 # 輸出:[<Element book at 0x289bac27048>, <Element book at 0x289bac27088>] page.xpath('//book[@category="WEB" and @cover="paperback"]') # 獲取同時擁有category和cover屬性的book標籤 page.xpath('//book[@category="WEB" or @cover="paperback"]') # 獲取擁有 category 或 cover 屬性的book標籤 page.xpath('//book[not(@category="cooking")]') # 獲取屬性不是category="cooking"的book標籤
5、親屬關係code
表達式 | 描述 |
parent::*
|
表示當前節點的父節點元素
|
child::*
|
表示當前節點的子元素
|
following-sibling::*
|
表示當前節點的後序全部兄弟節點元素
|
preceding-sibling::*
|
表示當前節點的前面全部兄弟節點元素
|
page.xpath('//book/parent::*') # 表示獲取book節點的父節點標籤 page.xpath('//book/child::*') # 表示獲取book節點的全部子節點 page.xpath('//book[1]/child::title') # 表示獲取第一個book節點下名稱爲title的子節點 page.xpath('//book[1]/following-sibling::*') # 表示獲取第一個book節點後序的兄弟節點(不包含自己) page.xpath('//book[3]/preceding-sibling::book') # 表示獲取第三個book節點前面的且名稱爲book的兄弟節點
6、經常使用函數xml
表達式 | 描述 |
last() |
返回當前上下文中的最後一個節點的位置號數。
|
contains()
|
模糊查詢 |
page.xpath('//book[last()]') # 獲取最後一個book標籤 page.xpath('//book[contains(@category, "co")]') # 模糊匹配屬性category="co"的book標籤