๐Ÿ Quick Reference for XPath + CSS

What are the different approaches to using XPath and CSS Selector?

Description
XPath
CSS Selector

Whole WebPage

/html

html

Whole WebPage body

/html/body

body

Image element

//img

img

Link

//a[@href = 'url']

a[href = 'url']

Direct Child

//div/a

div > a

Id

//tagName[@id=โ€™idValueโ€™]

tagName#idValue

Class

//tagName[@class=โ€™classValueโ€™]

tagName.Value of Class attribute

Attribute

//tagname[@attribute-name=โ€™value1โ€ฒ]

tagName[attribute=Value of attribute]

Multiple Attributes

//input[@type='submit' and @name='btnLogin']

tagname[attribute1='value1'][attribute2='value2']

Contains

//*[contains(@type,'sub')]

tagname[attribute*=substring]

Starts with

//tagname[starts-with(@attribute, โ€˜Start valueโ€™)]

tagname[attribute^=prefix of the String]

Ends with

//tagname[ends-with(@attribute, โ€˜End valueโ€™)]

tagname[attribute$=suffix of the String]

Matches

//*[matches(@type,'value')]

N/A

First Child

//ul[@id=โ€™listโ€™]/li[1]

ul#list li:first-child

Last Child

//ul[@id=โ€™listโ€™]/li[last()]

ul#list li:last-child

nth Child

//ul[@id=โ€™listโ€™]/li[3]

ul#list li:nth-child(3)

Text Value

//td[text()=โ€˜textname']

N/A

Element preceding some sibling

E2/preceding-sibling::E1

N/A

Sibling element immediately preceding

E/preceding-sibling::*[1]

N/A

User interface element that is disabled

E[@disabled]

E:disabled

Checkbox (or radio button) that is checked

//*[@checked]

*:checked

Text Value

//td[text()=โ€˜textname']

N/A

What are the differences between XPath and CSS locators?

Traversal:

โŽ XPath allows bidirectional traversal.

//div[@id='id']//preceding::input
//div[@id='id']//following::input

โžก๏ธ CSS only moves forward.

 div#id ~ input

๐Ÿ‘‰ So XPath has more powerful traversal.

Performance:

โœ… CSS selectors are faster since browsers optimize CSS.

Readability:

โœ… CSS locators are more concise and readable.

input[type='text']
//input[@type='text']

Last updated