本文根据 Devhints / Xpath 翻译。代码示例及版本范围沿用原文。
测试
Xpath 测试环境
在 Xpath 测试环境中进行查询测试:
- Xpath 测试环境 (whitebeam.org)
浏览器控制台
$x("//div")
适用于 Firefox 和 Chrome。
选择器
后代选择器
| CSS | Xpath | ? |
|---|---|---|
h1 | //h1 | ? |
div p | //div//p | ? |
ul > li | //ul/li | ? |
ul > li > a | //ul/li/a | |
div > * | //div/* | |
:root | / | ? |
:root > body | /body |
属性选择器
| CSS | Xpath | ? |
|---|---|---|
#id | //*[@id="id"] | ? |
.class | //*[@class="class"] …某种程度上 | |
input[type="submit"] | //input[@type="submit"] | |
a#abc[for="xyz"] | //a[@id="abc"][@for="xyz"] | ? |
a[rel] | //a[@rel] | |
a[href^='/'] | //a[starts-with(@href, '/')] | ? |
a[href$='pdf'] | //a[ends-with(@href, '.pdf')] | |
a[href*='://'] | //a[contains(@href, '://')] | |
a[rel~='help'] | //a[contains(@rel, 'help')] …某种程度上 |
顺序选择器
| CSS | Xpath | ? |
|---|---|---|
ul > li:first-of-type | //ul/li[1] | ? |
ul > li:nth-of-type(2) | //ul/li[2] | |
ul > li:last-of-type | //ul/li[last()] | |
li#id:first-of-type | //li[1][@id="id"] | ? |
a:first-child | //*[1][name()="a"] | |
a:last-child | //*[last()][name()="a"] |
兄弟元素
| CSS | Xpath | ? |
|---|---|---|
h1 ~ ul | //h1/following-sibling::ul | ? |
h1 + ul | //h1/following-sibling::ul[1] | |
h1 ~ #id | //h1/following-sibling::[@id="id"] |
jQuery
| CSS | Xpath | ? |
|---|---|---|
$('ul > li').parent() | //ul/li/.. | ? |
$('li').closest('section') | //li/ancestor-or-self::section | |
$('a').attr('href') | //a/@href | ? |
$('span').text() | //span/text() |
其他内容
| CSS | Xpath | ? |
|---|---|---|
h1:not([id]) | //h1[not(@id)] | ? |
| 文本匹配 | //button[text()="Submit"] | ? |
| 文本匹配(子字符串) | //button[contains(text(),"Go")] | |
| 算术运算 | //product[@price > 2.50] | |
| 包含子元素 | //ul[*] | |
| 包含子元素(特定) | //ul[li] | |
| “或”逻辑 | //a[@name or @href] | ? |
| 并集(合并结果) | //a | //div | ? |
类名检查
//div[contains(concat(' ',normalize-space(@class),' '),' foobar ')]
Xpath 不具备“检查是否属于空格分隔列表”的操作符,因此这是变通方案(来源).
表达式
步骤与轴
// | ul | / | a[@id='link'] |
| 轴 | 步骤 | 轴 | 步骤 |
前缀
| 前缀 | 示例 | 内容 |
|---|---|---|
// | //hr[@class='edge'] | 任意位置 |
./ | ./a | 相对 |
/ | /html/body/div | 根 |
表达式可以由其中任意一项开头。
轴
| 轴 | 示例 | 内容 |
|---|---|---|
/ | //ul/li/a | 子节点 |
// | //[@id="list"]//a | 后代 |
使用以下符号分隔步骤: /。如果不想仅选择直接子节点,可以使用两个(//)。
步骤
//div
//div[@name='box']
//[@id='link']
步骤可以包含元素名称(div)以及 谓词 ([...])。两者均为可选。此外,步骤还可以包含以下内容:
//a/text() #=> "Go home"
//a/@href #=> "index.html"
//a/* #=> All a's child elements
谓词
谓词
//div[true()]
//div[@class="head"]
//div[@class="head"][@id="top"]
在满足特定条件时,对节点集进行限制。谓词可以进行链式组合。
运算符
# Comparison
//a[@id = "xyz"]
//a[@id != "xyz"]
//a[@price > 25]
# Logic (and/or)
//div[@id="head" and position()=2]
//div[(x and y) or not(z)]
使用比较运算符和逻辑运算符来构建条件。
使用节点
# Use them inside functions
//ul[count(li) > 2]
//ul[count(li[@class='hide']) > 0]
# This returns `<ul>` that has a `<li>` child
//ul[li]
可以在谓词中使用节点。
索引
//a[1] # first <a>
//a[last()] # last <a>
//ol/li[2] # second <li>
//ol/li[position()=2] # same as above
//ol/li[position()>1] # :not(:first-of-type)
使用 [] 使用数字,或者 last() 或 position().
链式顺序
a[1][@href='/']
a[@href='/'][1]
顺序至关重要,以下两者含义不同。
嵌套谓词
//section[.//h1[@id='hi']]
如果存在满足条件的 <section> ,则返回 <h1> 后代节点(包含 id='hi'.
函数
节点函数
name() # //[starts-with(name(), 'h')]
text() # //button[text()="Submit"]
# //button/text()
lang(str)
namespace-uri()
count() # //table[count(tr)=1]
position() # //ol/li[position()=2]
布尔函数
not(expr) # button[not(starts-with(text(),"Submit"))]
字符串函数
contains() # font[contains(@class,"head")]
starts-with() # font[starts-with(@class,"head")]
ends-with() # font[ends-with(@class,"head")]
concat(x,y)
substring(str, start, len)
substring-before("01/02", "/") #=> 01
substring-after("01/02", "/") #=> 02
translate()
normalize-space()
string-length()
类型转换
string()
number()
boolean()
轴
使用轴
//ul/li # ul > li
//ul/child::li # ul > li (same)
//ul/following-sibling::li # ul ~ li
//ul/descendant-or-self::li # ul li
//ul/ancestor-or-self::li # $('ul').closest('li')
表达式中的步骤通过以下符号分隔: /,通常用于选取子节点。但并非总是如此:您可以通过指定不同的“轴”来改变选取方式。 ::.
// | ul | /child:: | li |
| 轴 | 步骤 | 轴 | 步骤 |
子轴
# both the same
//ul/li/a
//child::ul/child::li/child::a
child:: 是默认轴。这使得 //a/b/c 能够工作。
# both the same
# this works because `child::li` is truthy, so the predicate succeeds
//ul[li]
//ul[child::li]
# both the same
//ul[count(li) > 2]
//ul[count(child::li) > 2]
“后代或自身”(descendant-or-self)轴
# both the same
//div//h4
//div/descendant-or-self::h4
// 是……的简写 descendant-or-self:: 轴。
# both the same
//ul//[last()]
//ul/descendant-or-self::[last()]
其他轴
| 轴 | 缩写 | 说明 |
|---|---|---|
ancestor | ||
ancestor-or-self | ||
attribute | @ | @href 是……的简写 attribute::href |
child | div 是……的简写 child::div | |
descendant | ||
descendant-or-self | // | // 是……的简写 /descendant-or-self::node()/ |
namespace | ||
self | . | . 是……的简写 self::node() |
parent | .. | .. 是……的简写 parent::node() |
following | ||
following-sibling | ||
preceding | ||
preceding-sibling |
还有其他轴可供使用。
联合类型
//a | //span
使用 | 用于连接两个表达式。
更多示例
示例
//* # all elements
count(//*) # count all elements
(//h1)[1]/text() # text of the first h1 heading
//li[span] # find a <li> with an <span> inside it
# ...expands to //li[child::span]
//ul/li/.. # use .. to select a parent
Find 父级
//section[h1[@id='section-name']]
查找一个 <section> 直接包含……的元素 h1#section-name
//section[//h1[@id='section-name']]
查找一个 <section> 包含……的元素 h1#section-name。(与上文相同,但使用“后代或自身”轴而非“子级”轴)
最近(Closest)
./ancestor-or-self::[@class="box"]
其作用类似于 jQuery 的 $().closest('.box').
属性
//item[@price > 2*@discount]
查找 <item> 并检查其属性
参考资料
- Xpath 测试环境 (whitebeam.org)