阅读(2626) (0)

XPath 备忘单

2021-08-30 14:48:04 更新
这是一个XPath选择器备忘单,其中列出了常用的 XPath 定位方法和 CSS 选择器

XPath 选择器

入门

在 Firefox 或 Chrome 控制台中测试:

$x('/html/body')
$x('//h1')
$x('//h1')[0].innerText
$x('//a[text()="XPath"]')[0].click()

后代选择器

Xpath CSS
//h1 小时1
//div//p 分压
//ul/li ul > li
//ul/li/a ul > li > a
//div/* div > *
/ :根
/html/body :root > 身体

下标选择器

XpathCSS
//ul/li[1]ul > li:first-child
//ul/li[2]ul > li:nth-child(2)
//ul/li[last()]ul > li:last-child
//li[@id="id"][1]li#id:first-child
//a[1]a:first-child
//a[last()]a:last-child

属性选择器

XpathCSS
//*[@id="id"]#id
//*[@class="class"].class
//input[@type="submit"]input[type="submit"]
//a[@id="abc"][@for="xyz"]a#abc[for="xyz"]
//a[@rel]a[rel]
//a[starts-with(@href, '/')]a[href^='/']
//a[ends-with(@href, '.pdf')]a[href$='pdf']
//a[contains(@href, '://')]a[href*='://']
//a[contains(@rel, 'help')]a[rel~='help']

相邻兄弟选择

Xpath CSS
//h1/following-sibling::ul h1~ul
//h1/following-sibling::ul[1] h1 + ul
//h1/following-sibling::[@id="id"] h1 ~ #id

jQuery

Xpath CSS
//ul/li/.. $('ul > li').parent()
//li/ancestor-or-self::section $('li').closest('section')
//a/@href $('a').attr('href')
//span/text() $('span').text()

杂项选择器

XpathCSS
//h1[not(@id)]h1:not([id])
//button[text()="Submit"]Text match
//button[contains(text(),"Go")]Text contains (substring)
//product[@price > 2.50]Arithmetic
//ul[*]Has children
//ul[li]Has children (specific)
//a[@name or @href]Or logic
//a | //divUnion (joins results)

XPath 表达式

步骤(Step)和轴(Axis)

//ul/a[@id='link']
AxisStepAxisStep

前缀

字首 例子 意思
// //hr[@class='edge'] 任何地方
/ /html/body/div
./ ./div/p 相对的

例子 意思
/ //ul/li/a 孩子
// //[@id="list"]//a 后代

XPath 谓语

谓语

//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]
# 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-child)

使用[]带数字或last()position()

链式顺序

a[1][@href='/']
a[@href='/'][1]

顺序很重要,这两者是不同的。

嵌套谓语

//section[.//h1[@id='hi']]

<section>如果它有一个<h1>后代,返回id='hi'

XPath 函数

节点函数

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]

字符串函数

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

布尔函数

not(expr)         # button[not(starts-with(text(),"Submit"))]

类型转换

string()
number()
boolean()

XPath 轴

使用轴

//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
Axis Step Axis Step

表达式的步骤由 分隔/,通常用于选择子节点。这并不总是正确的:您可以使用::.

子轴

# 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 
//ul[li]
//ul[child::li]
# both the same
//ul[count(li) > 2]
//ul[count(child::li) > 2]

后代或自我轴

# 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

您还可以使用其他轴。

Union(|)运算符

//a | //span

使用|连接两个表达式。

XPath 更多例子

例子

//*                 # 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

获取父级

//section[h1[@id='section-name']]

找到一个<section>直接包含的h1#section-name

//section[//h1[@id='section-name']]

查找<section>包含h1#section-name. (同上,但使用后代或自我而不是孩子)

最近的

./ancestor-or-self::[@class="box"]

像 jQuery 的$().closest('.box').

属性

//item[@price > 2*@discount]

查找<item>并检查其属性

另见