xpath
(1)介紹
- 可在XML中查詢資訊
- 支援HTML的查詢
- 透過元素和屬性進行導航
pip install lxml
from lxml import etree
# 將原始碼轉化為能被XPath匹配的格式
selector = etree.HTML(原始碼)
# 返回為一列表
res = selector.xpath(表示式)
(2)使用
(1)路徑表示式
表示式 |
描述 |
例項 |
解析 |
/ |
從根節點選取 |
/body/div[1] |
選取根結點下的body下的第一個div標籤 |
// |
從匹配選擇的當前節點選擇文件中的節點,而不考慮它們的位置 |
//a |
選取文件中所有的a標籤 |
./ |
當前節點再次進行xpath |
./a |
選取當前節點下的所有a標籤 |
@ |
選取屬性 |
//@calss |
選取所有的class屬性 |
- 直接使用xpath語法查詢出來的是Element物件,所以要使用for迴圈繼續xpath
text()
獲取標籤中的文字值
from lxml import etree
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
selector = etree.HTML(html_doc)
res = selector.xpath("//a")
print(res) # [<Element a at 0x2155de71640>, <Element a at 0x2155e3976c0>, <Element a at 0x2155e397800>]
for result in res:
href = result.xpath('./@href')
href1 = result.xpath('./@href')[0] # 獲取標籤裡的href值
href2 = result.xpath('./text()')[0] # 獲取標籤裡的文字值
print(href)
# ['http://example.com/elsie'] ['http://example.com/lacie'] ['http://example.com/tillie']
print(href1)
# http://example.com/elsie http://example.com/lacie http://example.com/tillie
print(href2)
# Elsie Lacie Tillie
(2)謂語
- 謂語用來查詢某個特定的節點或者包含某個指定的值的節點。
- 謂語被嵌在方括號中。
- 在下面的表格中,我們列出了帶有謂語的一些路徑表示式,以及表示式的結果:
路徑表示式 |
結果 |
/ul/li[1] |
選取屬於 ul子元素的第一個 li元素。 |
/ul/li[last()] |
選取屬於 ul子元素的最後一個 li元素。 |
/ul/li[last()-1] |
選取屬於 ul子元素的倒數第二個 li元素。 |
//ul/li[position()❤️] |
選取最前面的兩個屬於 ul元素的子元素的 li元素。 |
//a[@title] |
選取所有擁有名為 title的屬性的 a元素。 |
//a[@title='xx'] |
選取所有 a元素,且這些元素擁有值為 xx的 title屬性。 |
//a[@title>10] > < >= <= != |
選取 a元素的所有 title元素,且其中的 title元素的值須大於 10。 |
/body/div[@price>35.00] |
選取body下price元素值大於35的div節點 |
(3)選取未知節點
【1】語法
- XPath 萬用字元可用來選取未知的 XML 元素。
萬用字元 |
描述 |
* |
匹配任何元素節點。 |
@* |
匹配任何屬性節點。 |
node() |
匹配任何型別的節點。 |
【2】例項
- 在下面的表格中,我們列出了一些路徑表示式,以及這些表示式的結果:
路徑表示式 |
結果 |
/ul/* |
選取 bookstore 元素的所有子元素。 |
//* |
選取文件中的所有元素。 |
//title[@*] |
選取所有帶有屬性的 title 元素。 |
//node() |
獲取所有節點 |
(4)模糊查詢
//div[contains(@id, "he")]