logo
🛠️ 开发工具

XPath

XPath Cheat Sheet - 快速参考指南,收录常用语法、命令与实践。

📂 分类 · 开发工具🧭 Markdown 速查🏷️ 2 个标签
#xpath#xml
向下滚动查看内容
返回全部 Cheat Sheets

XPath Selectors

Getting started

Test in Firefox or Chromium based browser console:

CONSOLE
滚动查看更多
$x('/html/body')
$x('//h1')
$x('//h1')[0].innerText
$x('//a[text()="XPath"]')[0].click()
Descendant selectors
XpathCSS
//h1h1
//div//pdiv p
//ul/liul > li
//ul/li/aul > li > a
//div/*div > *
/:root
/html/body:root > body

{.show-header}

Order selectors
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

{.show-header}

Attribute selectors
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']

{.show-header}

Siblings
XpathCSS
//h1/following-sibling::ulh1 ~ ul
//h1/following-sibling::ul[1]h1 + ul
//h1/following-sibling::[@id="id"]h1 ~ #id

{.show-header}

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

{.show-header}

Misc selectors

| Xpath | CSS | | --------------------------------- | ------------------------- | --------------------- | | //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 | //div | Union (joins results) |

{.show-header}

XPath Expressions

Steps and axes
<br/>
----
//ul/a[@id='link']
AxisStepAxisStep

{.left-text}

Prefixes
PrefixExampleMeans
////hr[@class='edge']Anywhere
//html/body/divRoot
././div/pRelative

{.show-header}

Axes
AxisExampleMeans
///ul/li/aChild
////[@id="list"]//aDescendant

{.show-header}

XPath Predicates

Predicates
BASH
滚动查看更多
//div[true()]
//div[@class="head"]
//div[@class="head"][@id="top"]

Restricts a nodeset only if some condition is true. They can be chained.

Operators
BASH
滚动查看更多
# Comparison
//a[@id = "xyz"]
//a[@id != "xyz"]
//a[@price > 25]
BASH
滚动查看更多
# Logic (and/or)
//div[@id="head" and position()=2]
//div[(x and y) or not(z)]
Using nodes
BASH
滚动查看更多
# Use them inside functions
//ul[count(li) > 2]
//ul[count(li[@class='hide']) > 0]
BASH
滚动查看更多
# Returns `<ul>` that has a `<li>` child
//ul[li]

You can use nodes inside predicates.

Indexing
BASH
滚动查看更多
//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)

Use [] with a number, or last() or position().

Chaining order
BASH
滚动查看更多
a[1][@href='/']
a[@href='/'][1]

Order is significant, these two are different.

Nesting predicates
CODE
滚动查看更多
//section[.//h1[@id='hi']]

This returns <section> if it has an <h1> descendant with id='hi'.

XPath Functions

Node functions
BASH
滚动查看更多
name()            # //[starts-with(name(), 'h')]
text()            # //button[text()="Submit"]
                  # //button/text()
lang(str)
namespace-uri()
BASH
滚动查看更多
count()           # //table[count(tr)=1]
position()        # //ol/li[position()=2]
String functions
BASH
滚动查看更多
contains()        # font[contains(@class,"head")]
starts-with()     # font[starts-with(@class,"head")]
ends-with()       # font[ends-with(@class,"head")]
BASH
滚动查看更多
concat(x,y)
substring(str, start, len)
substring-before("01/02", "/")  #=> 01
substring-after("01/02", "/")   #=> 02
translate()
normalize-space()
string-length()
Boolean functions
BASH
滚动查看更多
not(expr)         # button[not(starts-with(text(),"Submit"))]
Type conversion
BASH
滚动查看更多
string()
number()
boolean()

XPath Axes

Using axes
BASH
滚动查看更多
//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
AxisStepAxisStep

{.left-text}

Steps of an expression are separated by /, usually used to pick child nodes. That's not always true: you can specify a different "axis" with ::.

Child axis
BASH
滚动查看更多
# both the same
//ul/li/a
//child::ul/child::li/child::a

child:: is the default axis. This makes //a/b/c work.

BASH
滚动查看更多
# both the same
# this works because `child::li` is truthy
//ul[li]
//ul[child::li]
BASH
滚动查看更多
# both the same
//ul[count(li) > 2]
//ul[count(child::li) > 2]
Descendant-or-self axis
BASH
滚动查看更多
# both the same
//div//h4
//div/descendant-or-self::h4

// is short for the descendant-or-self:: axis.

BASH
滚动查看更多
# both the same
//ul//[last()]
//ul/descendant-or-self::[last()]
Other axes
AxisAbbrevNotes
ancestor
ancestor-or-self
attribute@@href is short for attribute::href
childdiv is short for child::div
descendant
descendant-or-self//// is short for /descendant-or-self::node()/
namespace
self.. is short for self::node()
parent.... is short for parent::node()
following
following-sibling
preceding
preceding-sibling

{.headers}

There are other axes you can use.

Unions
BASH
滚动查看更多
//a | //span

Use | to join two expressions.

XPath More examples

Examples
BASH
滚动查看更多
//*                 # 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 a parent
BASH
滚动查看更多
//section[h1[@id='section-name']]

Finds a <section> that directly contains h1#section-name

BASH
滚动查看更多
//section[//h1[@id='section-name']]

Finds a <section> that contains h1#section-name. (Same as above, but uses descendant-or-self instead of child)

Closest
BASH
滚动查看更多
./ancestor-or-self::[@class="box"]

Works like jQuery's $().closest('.box').

Attributes
BASH
滚动查看更多
//item[@price > 2*@discount]

Finds <item> and check its attributes

Also see

相关 Cheat Sheets

1v1免费职业咨询
logo

Follow Us

linkedinfacebooktwitterinstagramweiboyoutubebilibilitiktokxigua

We Accept

/image/layout/pay-paypal.png/image/layout/pay-visa.png/image/layout/pay-master-card.png/image/layout/pay-airwallex.png/image/layout/pay-alipay.png

地址

Level 10b, 144 Edward Street, Brisbane CBD(Headquarter)
Level 2, 171 La Trobe St, Melbourne VIC 3000
四川省成都市武侯区桂溪街道天府大道中段500号D5东方希望天祥广场B座45A13号
Business Hub, 155 Waymouth St, Adelaide SA 5000

Disclaimer

footer-disclaimerfooter-disclaimer

JR Academy acknowledges Traditional Owners of Country throughout Australia and recognises the continuing connection to lands, waters and communities. We pay our respect to Aboriginal and Torres Strait Islander cultures; and to Elders past and present. Aboriginal and Torres Strait Islander peoples should be aware that this website may contain images or names of people who have since passed away.

匠人学院网站上的所有内容,包括课程材料、徽标和匠人学院网站上提供的信息,均受澳大利亚政府知识产权法的保护。严禁未经授权使用、销售、分发、复制或修改。违规行为可能会导致法律诉讼。通过访问我们的网站,您同意尊重我们的知识产权。 JR Academy Pty Ltd 保留所有权利,包括专利、商标和版权。任何侵权行为都将受到法律追究。查看用户协议

© 2017-2025 JR Academy Pty Ltd. All rights reserved.

ABN 26621887572