How To Write Xpath Expression In Dynamic Way

Steps to write Xpath expression in dynamic way

  • Identify the dependent and independent element.

Example : Flipkart -> Books and Media -> Books -> The oath of vayuputras

Dependent element = Rs 211 (Price)

Independent element : Name of the book

  • Right click on the independent element and inspect with firebug.
  • Write the xpath expression using the attribute or function for independent element.

Ex : //a[contains(text(),’The oath of vayuputras’)]

  • From independent element, find the common parent for the dependent as well as independent element.
  • From the common parent, write down the entire tree-structure(Note: Trick is place your mouse on independent element, move the cursor upward till both dependent and independent elements are highlighted.
  • From common parent, write down the entire tree-structure.


  • From independent element, write xpath till common parent.

NOTE: Single forward slash is used to identify the immediate child whereas ‘[ ]’ is used to identify the parent of the child element.

Keep on using ‘/ ‘ to identify immediate child i.e; move forward. Use ‘[ ]’ to move backward.

The trick here is from common parent, write xpath till independent element.

Ex:  //div/div[1]/a[contains(text(),’Vayuputra’)]

Now, for the above expression, replace ‘ / ‘ with square bracket [].


  • Write xpath expression for the dependent element.

//span[text()=’Rs 211’]

  • From common parent write xpath expression till dependent element.


/div[3]/div[2]/div[1]/span[text()=’Rs. 211’]


  • The above xpath expression is still not in dynamic way. To do that from the common parent , delete entire thing till span tag and replace with ‘//’.
  • Whenever we are using the index, remove the index.

NOTE : While modifying the xpath expression in more dynamic way, use common sense. 😉

Rule 1 : While writing xpath expression in dynamic way, bridge the connection between independent, common  parent and dependent element to achieve the ultimate goal of finding dependent element.


Add Comment