White Box Testing
Test your code
   Home      selenium2WebDriver-XPath-Selector-Cheatsheet
 
XPath Selector CheatSheet


XPath selector constructed using xml path, HTML tags, HTML tags attribute and DOM.  Usually we use XPath selector when we don’t find any option to select element uniquely by name, id or link.
 
XPath selector is easy to read and used frequently to locate dynamic and complex element.
 
There are two types of xpath
 
Absolute XPath: Start with single forward slash(/) and used to select element from root
 
Relative XPath: Start with double forward slash(//) and used to select element anywhere in the page
 
<ul type="text" id="type_vehicle_cat" name="vehicle_name" style="style_name" class="myForm text_primary summary">
   <li>Bycycle</li>
   <li>Car</li>
   <li>Bus</li>
<ul>

 
Direct child element
xpath=//ul/a

 
Sub child element
xpath=//ul//a

 
Element by attribute(@ for attribute selector)
xpath=//ul[@id=’type_vehicle_cat’]

 
Element by AND, OR conditional expression
xpath=//ul[@name=’vehicle_name’ AND @style=’style_name’]
xpath=//*[@name=’vehicle_name’ OR @style=’style_name’]

 
Element by starts-with method
xpath=//ul[starts-with(@id, ‘type’)]

 
Element by contains method
xpath=//ul[contains(@id, ‘_vehicle_’)]

 
Element by text method
xpath=//li[text()=’Bycycle’]

 
To select first child element
xpath=//ul[@id=’type_vehicle_cat’]/li[first()]
xpath=//ul[@id=’type_vehicle_cat’]/li[1]

 
To select intermediate child element
xpath=//ul[@id=’type_vehicle_cat’]/li[2]

 
To select last child element
xpath=//ul[@id=’type_vehicle_cat’]/li[last()]
xpath=//ul[@id=’type_vehicle_cat’]/li[3]

 
XPath axes methods
Used to find dynamic elements
ancestor - Selects all ancestors (parent, grandparent, etc.) of the current node
ancestor-or-self - Selects all ancestors (parent, grandparent, etc.) of the current node and the current node itself
attribute - Selects all attributes of the current node
child - Selects all children of the current node
descendant - Selects all descendants (children, grandchildren, etc.) of the current node
descendant-or-self - Selects all descendants (children, grandchildren, etc.) of the current node and the current node itself
following - Selects everything in the document after the closing tag of the current node
following-sibling - Selects all siblings after the current node
namespace - Selects all namespace nodes of the current node
parent - Selects the parent of the current node
preceding - Selects all nodes that appear before the current node in the document, except ancestors, attribute nodes and namespace nodes
preceding-sibling - Selects all siblings before the current node
self - Selects the current node
 
child::*
Selects all children of the current node
 
child::li
Select all li nodes that are children of the current node
 
//ul[@id=’type_vehicle_cat’]/child::li
Select all li nodes that are children of the current node ul