XPath 簡介:
- XPath 是一門在 XML 文檔中查找信息的語言
什么是 XPath?
- XPath 使用路徑表達(dá)式在 XML 文檔中進(jìn)行導(dǎo)航
- XPath 包含一個標(biāo)準(zhǔn)函數(shù)庫
- XPath 是 XSLT 中的主要元素
- XPath 是一個 W3C 標(biāo)準(zhǔn)
事例:
etree_html = etree.HTML(html)
print(etree_html)
# 匹配所有節(jié)點 //*
result = etree_html.xpath('//*')
# 匹配所有子節(jié)點 //a 文本獲取:text()
result = etree_html.xpath('//a/text()')
print(result)
# 查找元素子節(jié)點 /
result_article = etree_html.xpath('//div[@class="pic"]/p/text()') #獲取文章
print(result_article)
from_name = etree_html.xpath('//div[@class="source"]//span[@class="from"]/a/text()') # 獲取名字
from_address = etree_html.xpath('//div[@class="source"]//span[@class="from"]/a/@href') # 獲取地址
# 查找元素所有子孫節(jié)點 //
result_title = etree_html.xpath('//div[@class="channel-item"]//h3/a/text()') # 獲取標(biāo)題
# print(result_son)
# 父節(jié)點 ..
result = etree_html.xpath('//span[@class="pubtime"]/../span/a/text()')
print(result)
# 屬性匹配 [@class="xxx"]
# 文本匹配 text() 獲取所有文本//text()
result = etree_html.xpath('//div[@class="article"]//text()')
print(result)
# 屬性獲取 @href
result = etree_html.xpath('//div[@class="bd"]/h3/a/@href')
print(result)
# 屬性多值匹配 contains(@class 'xx')
result = etree_html.xpath('//div[contains(@class, "grid-16-8")]//div[@class="likes"]/text()[1]')
print(result)
# 多屬性匹配 or, and, mod, //book | //cd, + - * div = != < > <= >=
result = etree_html.xpath('//span[@class="pubtime" and contains(text(), "09-07")]/text()')
print(result)
# 按序選擇 [1] [last()] [poistion() < 3] [last() -2]
# 節(jié)點軸
//li/ancestor::* 所有祖先節(jié)點
//li/ancestor::div div這個祖先節(jié)點
//li/attribute::* attribute軸,獲取li節(jié)點所有屬性值
//li/child::a[@href="link1.html"] child軸,獲取直接子節(jié)點
//li/descendant::span 獲取所有span類型的子孫節(jié)點
//li/following::* 選取文檔中當(dāng)前節(jié)點的結(jié)束標(biāo)記之后的所有節(jié)點
//li/following-sibling::* 選取當(dāng)前節(jié)點之后的所用同級節(jié)點
# 同時取到節(jié)點和元素
result = etree_html.xpath('//div[@class="channel-item"] | //span[@class="pubtime"]/../span/a/text()')
推薦一款插件 Xpath Helper:
Xpath Helper 是一種結(jié)構(gòu)化網(wǎng)頁元素選擇器,支持列表和單節(jié)點數(shù)據(jù)獲取,
它可以快速地定位網(wǎng)頁元素。
對比 Beautiful Soup,由于 Xpath 網(wǎng)頁元素查找性能更有優(yōu)勢;Xpath 相比正則表達(dá)式編寫起來更方便。
編寫 Xpath 之后會實時顯示匹配的數(shù)目和對應(yīng)的位置,方便我們判斷語句是否編寫正確。
image.png