The xpath of the element keeps changing, how do I find dynamic xpath for this element in Selenium


We can find the xpath of the element that keeps changing with the help of the xpath functions. They help to identify an element having dynamic attribute value or text. Some of these functions are listed below −

  • text() – Identifies an element with the help of the visible text on the page. The xpath expression for the element Home is //*[text()='Home'].

  • starts-with – Identifies an element whose attribute value begins with a specific text. This function is normally used for attribute values which are dynamic in nature.

    The xpath expression of Home is //a[starts-with(@title, 'Questions &')].

  • contains - Identifies an element whose attribute value contains a sub-text of the actual attribute value. This function is normally used for attribute values which are dynamic in nature.

    The xpath expression of Home//a[contains(@title, 'Questions & Answers')].

We can also create a dynamic xpath with the help of single or multiple attributes with the format −

//tagname[@attribute='value'] – with one attribute
//tagname[@attribute1='value'][@attribute2='value'] – with more than one attributes.

Syntax

//img[@alt='Tutorialspoint']

Syntax

//img[@alt='Tutorialspoint'] [@title='Tutorialspoint']

We can also create a dynamic xpath with the help of ORand AND operations on attributes with the format −

//tagname[@attribute1='value' or @attribute2='value']
//tagname[@attribute1='value' and @attribute2='value']

Syntax

//img[@alt='Tutorialspoint' or @name='Tutorial']
//img[@alt='Tutorialspoint' and @id='txt']

Updated on: 06-Apr-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements