XPath Selenium tactics will help you to write effective selenium find by statements especially for locating dynamic web elements in selenium webdriver projects. Generally, test automation engineers struggle to write dynamic XPath at the beginning of their test automation journeys. To address this pain, I prepared this tutorial for writing effective XPath in Selenium.

I shared all my tactics such as XPath contains text, sibling, ancestor, childpreceding, descendant, parent, and so on. I hope this article will help you to write smart and non-brittle selenium find by statements in your projects. Let’s start!

Dynamic Web Elements

In our test automation codes, we generally prefer to use id, name, class, etc. these kinds of locators. However, sometimes we could not find any of them in the DOM and also sometimes locators of some elements change dynamically in the DOM. In these kinds of situations, we need to use smart locators. These locators must be capable to locate complex and dynamically changing web elements. In below sections, I will share with you 15 tactics to write effective XPath locators.

XPath Selenium Selectors

We can find the location of any element on a web page using XML path expressions. The basic syntax for XPath is shown below:

Syntax = //tagname[@attribute=’Value‘]

Example = //input[@id=’user-message‘]

xpath-selenium

You can also use class, name, link text, and the other attributes to locate an element with XPath as shown above.

Absolute and Relative XPath

Generally, in some test automation engineer interviews, I asked the difference between absolute and relative XPath. Actually, it is the answer is very easy.

Absolute XPath

  • It is a direct way to locate an element.
  • It is very brittle.
  • Starts with single slash “/” that means starting to search from the root.

Example: /html/body/div[2]/div/div[2]/div[1]/div[2]/form/div/input

xpath in selenium

Relative XPath

  • Starts from the middle of the HTML DOM.
  • Starts with a double slash “//” that means it can start to search anywhere in the DOM structure.
  • Shorter than Absolute XPath.
  • Less fragile.

Example: //div[@class=’form-group’]//input[@id=’user-message’]

dynamic xpath

Example: //*[@class=’panel-body’]//li[contains(text(),’entered in input field’)]

xpath contains

Writing Smart XPaths for Complex and Dynamic Elements

Tag – Attribute – Value Trio

Syntax: //tag[@attribute=’value‘]

Example: //input[@id, ‘user-message’]