# What is xpath in Selenium?

Software TestingAutomation TestingSelenium Web Driver

Xpath is one of the most important locators used in Selenium for identifying web elements. It works in the following ways −

• It navigates through the Document Object Model (DOM) with the help of elements and their attributes for identification.

• Although it helps to locate the elements uniquely, it is slower in terms of speed from the other locators.

An xpath is represented by two ways namely ‘/ ‘and ‘// ‘. A forward single slash means absolute path. Here xpath traverses direct from parent to child in DOM. Thus in absolute xpath we have to travel from the root node to the target.

Syntax −

driver.findElement(By.xpath("/html/body/div/input")).

A double forward ‘// ‘slash means relative path. Here xpath finds the matching element in every corner of DOM. It doesn't have a particular beginning point.

Syntax −

driver.findElement(By.xpath("//input[@name=’Tutorial’]")).


It is always recommended to use relative xpath rather than absolute xpath. In absolute xpath, we need to specify from the root to the desired element so if any of the attributes and its value get changed in between, then our xpath will no longer be correct.

Syntax for xpath

//tagname[@attribute=’value’] or //*[@attribute=’value’]

Xpath basically locates elements with the help of XML path. XML known as the Extensible Markup Language.

Published on 10-Jun-2020 16:43:52