Cheatsheet for XPath with some CSS Selectors
few minutes
selenium
cheatsheetselenium
Beginner
test automation engineer
In Browser's console

$("[CSS Selector]")
$x("[XPath expression]")

Descendents
CSS SelectorXPath Expression
tagname//elementname
div p//div//p
ol > li//ol/li
ol > li > p//ol/li/p
div > *//div/*
:root/
Siblings
CSS SelectorXPath Expression
h1 ~ p//h1/following-sibling::p
h1 + p//h1/following-sibling::p[1]
h1 ~ #id//h1/following-sibling::[@id="id"]
Attributes
CSS SelectorXPath Expression
#id//[@id="id"]
.classname//*[@class="classname"]
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')]
Order
CSS SelectorXPath Expression
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"]
Other XPath
XPath SyntaxMeaning
/root
//anywhere
.relative

//h1[not(@id)] //button[text()="Submit"]
//button[contains(text(),"Go")]
//product[@price > 2.50]
//ul[*]
//ul[li]
//a[@name or @href]
//div[contains(concat(' ',normalize-space(@class),' '),' foobar ')]
//a | //span

//div[@id = "myid"]
//div[@id != "myid"]
//a[@price > 100]
//div[@id="myid" and position()=2]
//div[(x and y) or not(z)]
//ul[count(li) > 2]
//ul[count(li[@class='someclass']) > 0]
//ul[li]
//a[1]
//a[last()]
//ol/li[2]
//ol/li[position()=2]
//ol/li[position()>1]
:not(:first-of-type) (same as above)
a[1][@href='/']
a[@href='/'][1] (different than above)
//section[.//h1[@id='hi']]

//*
(//h1)[1]/text()
//li[span]

//ul/li/..
use .. to select a parent

XPath Functions

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

XPath Axis

child:: is the default axis
//ul/li
//ul/child::li (same as above)
//ul/following-sibling::li
//ul/descendant-or-self::li
//ul/ancestor-or-self::li

ancestor
ancestor-or-self

attribute @
@href is short for attribute::href

child
div 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