๐ Quick Reference for XPath + CSS
What are the different approaches to using XPath and 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.
โก๏ธ CSS only moves forward.
๐ So XPath has more powerful traversal.
Performance:
โ CSS selectors are faster since browsers optimize CSS.
Readability:
โ CSS locators are more concise and readable.
Last updated