top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

Ways to write XPath in Selenium

XPath is an XML path used for navigation through the HTML structure of the page.

In Selenium, if the elements are not found by the general locators like Id, Class,Name,etc,

then XPath is used to find that element on the web page.


There are two types of XPath, Absolute XPath and Relative XPath.

  • Absolute XPath:

It refers to the direct way of finding an element. The XPath begins with a single forward-slash (/), which states that the element can be selected from the root node

Example: /html/body/div[1]/div/div[1]/a


  • Relative XPath:

It is a type of XPath used to search an element node anywhere that exist on the web page. It is specified by the double forward slash notation (//) .

Example: xpath=//tagname[@attribute='value']


tag name --> represents the HTML tags like input, div, button

attribute --> represents the attributes like id, class, text

value --> represents the value of the attribute


Ways to write the XPath:


Below are some of the ways in which the XPath can be written to find the elements on

any webpage.


1. Locating elements with known attribute

Syntax : //*[@attributename='value']

Example: //*[@id='Username']


2. Locating elements with known element and attributes

Syntax : //tagname[@attributename='value']

Example: //input[@id='Username']


3. Locating elements with known visible text

Syntax : //tagname[text()='value']

Example: //input[text()='Blue Bird']


4. Locating elements with when part of the visible text is known

Syntax : //tagname[contains(text(),'value')]

Example: //input[contains(text(),'Blue')]


5. Locating elements with multiple attributes

Syntax : //*[@attribute1='value1'] [@attribute2='value2'].....[@attributeN='valueN']

Example: //*[@class='button'] [@type='submit'][@value='login']

With XPath, you can efficiently interact with web elements and perform accurate automation testing.

There could be so many of ways to write an XPath, but choosing the right one is the most important part as that determines the stability of your test cases and overall framework.

Happy learning!!!





43 views0 comments
bottom of page