Xpath Cheatsheet
Xpath Cheatsheet
Xpath Cheatsheet
IO Edit
# Selectors
Descendant selectors Attribute selectors
ul >match
Text li:nth-of-type(2) //ul/li[2]
//button[text()="Submit"] ? $('li').closest('section')
h1 + ul //h1/following-sibling::ul[1]
//li/ancestor-or-self::section
Xpath doesn’t have the “check if part of space-separated list” operator, so this is the
ul >match
Text (substring)
li:last-of-type //ul/li[last()]
//button[contains(text(),"Go")] h1 ~ #id (source).
workaround
$('a').attr('href') //h1/following-sibling::[@id="id"]
//a/@href ?
Arithmetic
li#id:first-of-type //li[1][@id="id"]> 2.50]
//product[@price ? $('span').text() //span/text()
Has children
a:first-child //*[1][name()="a"]
//ul[*]
# Expressions
Steps and axes Prefixes
Axes
// ul / a[@id='link'] Prefix
Steps Example What
# Predicates
Predicates Operators
//div[true()] # Comparison
//div[@class="head"] //a[@id = "xyz"]
//div[@class="head"][@id="top"] //a[@id != "xyz"]
//a[@price > 25]
Using
Chaining
nodes
Restricts a order
nodeset only if some condition is true. They can be chained. Indexing
Nesting
# Logicpredicates
(and/or)
//div[@id="head" and position()=2]
//div[(x and y) or not(z)]
# Use them inside functions
a[1][@href='/'] //a[1]
//section[.//h1[@id='hi']]
# first <a>
//ul[count(li) > 2]
a[@href='/'][1] //a[last()] # last <a>
//ul[count(li[@class='hide']) > 0] Use comparison and logic operators
//ol/li[2] to make
# second <li>conditionals.
This returns <section> if it has
//ol/li[position()=2] # an asdescendant
<h1>
same above with id='hi'.
Order is significant, these two are different. //ol/li[position()>1] # :not(:first-of-type)
# This returns `<ul>` that has a `<li>` child
//ul[li]
Use [] with a number, or last() or position().
# Functions
Node functions Boolean functions
# Axes
Using axes Child axis
Steps of an expression are separated by /, usually used to pick child nodes. That’s not
# both the same
always true: you can specify a different “axis” with ::.
# this works because `child::li` is truthy, so the predicate succeeds
//ul[li]
// ul /child:: li //ul[child::li]
ancestor
//a
// is |short
//span
for the descendant-or-self:: axis.
ancestor-or-self
Use | to the
# both join two expressions.
same attribute @ @href is short for attribute::href
//ul//[last()]
//ul/descendant-or-self::[last()] child div is short for child::div
descendant
namespace
following
following-sibling
preceding
preceding-sibling
# More examples
Examples Find a parent
Works like jQuery’s $().closest('.box'). Finds <item> and check its attributes
//section[//h1[@id='section-name']]
# References
Xpath test bed (whitebeam.org)
Devhints home
Applinks HTML emails Vim Vim scripting
cheatsheet cheatsheet cheatsheet cheatsheet