Skip to main content

In Selenium WebDriver A Complete Guide

Saurabh Dhariwal

Saurabh Dhariwal

Dynamic XPath In Selenium WebDriver - A Complete Guide

As we have described before how to find XPath in the browser, here we are going to describe different dynamic XPath functions.

 

Dynamic XPath

Dynamic XPath is also called as custom XPath and it is one way to locate element uniquely.  

Dynamic XPath is used to locate exact attribute or decrease the number of matching nodes/result from a webpage and following XPath expressions can be used for the same:

  • Contains
  • Sibling
  • Ancestor

Contains

Contains is used to locate the web element who matches the specific text from multiple blocks.  

As per the below image, if in your web page, there are sections that have the same element for all row, then you can find the specific element by using Contains to select text in that row.

a
Example: 

.//*[@class='product']//h4[contains(text(),'Text')]//ancestor::div[@class='table-good']
.//*[@class='product']//h4[contains(.,'Text')]//ancestor::div[@class='table-good']

Sibling

As the meaning of sibling, we can use this to find an element which is related to some other element. There are basically two types of sibling function which are used in XPath.

A) Preceding Sibling - If we select one sibling from given list, the “preceding sibling” function takes the preceding options of the selected one.

i
Example:

//ul[@class="OPENCR_flex_containerleft"]//li[@class="OPENCR_flex_box-other"]//select[@name="sort"]//option[contains (text(), 'by title')]/preceding-sibling::option

B) Following Siblings - If we select one sibling from given list, the “following sibling” function takes the following options of selected one.

Example:

w
//ul[@class="OPENCR_flex_containerleft"]//li[@class="OPENCR_flex_box-other"]//select[@name="sort"]//option[contains (text(), 'by title')]/following-sibling::option

Ancestor

We can use this to find an element on basis of the parent element. 
As per below image, if in your web page there is a section which has a same element for all the rows then you can find one row element by using ancestor.

q
Example: In this example, we are trying to find the first row on the basis of text in the row.         

//*[text()=’Text']//ancestor::div[@class='table-goods']

Hope you find this info. regarding Selenium helpful and you can also check this informative blog for Automation Script In Selenium IDE

Hire Us