XPath Selenium Selectors

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:

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

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

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’]

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

Writing Smart XPaths for Complex and Dynamic Elements

1) Writing XPath with Tag & Attribute & Value Trio

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

Examples:

2) Writing XPath with contains()

It is very handy XPath Selenium locator and sometimes it saves the life of a test automation engineer. When an attribute of an element is dynamic, then you can use contains() for the constant part of the web element but also you can use contains() in any condition when you need.

Example: //input[contains(@id, ‘er-messa’)]

Examples:

3) Writing XPath with starts-with

This method checks the starting text of an attribute. It is very handy to use when the attribute value changes dynamically but also you can use this method for non-changing attribute values.

Example: //input[starts-with(@id, ‘user’)]

4) Writing XPath with Chained XPaths Declerations

We can chain multiple relative XPath declarations with “//” double slash to find an element location as shown below.

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

5) Writing XPath with “and Statement

In this method, we use two interrogation conditions such as A and B and return a result-set as shown below:

Example: //*[@id=’user-message’ and @class=’form-control’]

6) Writing XPath with text()

We can find an element with its exact text.

Example: .//label[text()=’Enter message’]

 

2 thoughts to “XPath Selenium Selectors”

  1. Hello. I have checked your devxperts.net and i see you’ve got
    some duplicate content so probably it is the reason that you don’t rank hi in google.
    But you can fix this issue fast. There is a tool
    that generates articles like human, just search in google: miftolo’s tools

Leave a Reply

Your email address will not be published. Required fields are marked *