XPATH Cheat Sheet - aclaudio123/selenium-tutorial GitHub Wiki

XPATH Cheat Sheet

EIt's important to know that not every element on a page would have a static id, unique name, unique link text etc. For those elements without unique identifiers, we need to build customized CSS selectors or XPath to find and perform actions on them. Whatever we use, it should always be unique and find one matching node unless we want to capture a list of elements.

Difference between single ‘/’ or double ‘//’

Single slash ‘/’ -> look for the element immediately inside the parent element (first child). Double slash ‘//’ -> look for any child or nested-child elements inside the DOM.

Syntax:

//tag[@attribute='value']

to practice, check out http://letskodeit.teachable.com/pages/practice

XPath using single ‘/’ for Login link
//div[@id='navbar']/div/div/div/ul/li[2]/a

XPath using double ‘//’ for Login link.
//div[@id='navbar']//ul/li[2]/a

Note: inspecting and copying XPath using a browser you might get something like //*[@id='navbar']//ul/li[2]/a My advice will be to always replace the "*" with the right tag name.

Using Text of the element to build xpath

Finding Login link:

Syntax: 
//tag[text()='value'] 
 
//div[@class='homepage-hero']//a[text()='Enroll now']
//a[text()='Enroll now']

Using Contains to find the elements:

Syntax: 
//tag[contains(attribute, ‘value’)]

Finding Login link:
//div[@id='navbar']//a[contains(text(),'Login')]
//div[@id='navbar']//a[contains(@class,'navbar-link') and contains(@href,'sign_in')]

Using Starts-With to find the elements:

Syntax: 
//tag[starts-with(attribute, ‘value’)]

Finding Login link:
//div[@id='navbar']//a[starts-with(@class,'navbar-link')] 
//a[starts-with(@class,'navbar-link')]

Parent

Syntax: 
xpath-to-some-element//parent::<tag>

Preceding Sibling

Syntax:
 xpath-to-some-element//preceding-sibling::<tag>

Following Sibling

Syntax: xpath-to-some-element//following-sibling::<tag>

Exercise:

Find the price of the course “Python Programming Language”

Solution:

//table[@id='product']//td[text()='Python Programming Language']//following-sibling::td



For more CSS tips:

http://saucelabs.com/resources/articles/selenium-tips-css-selectors

⚠️ **GitHub.com Fallback** ⚠️