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

All About Locating Web Elements using Xpath

Introduction:


Locating Web elements using XPath is the most common and powerful mechanism. In one of the previous blogs, I discussed CSS Selectors. In this blog, we will try to cover everything which is required to know to be an expert in writing Xpath.


The following are the points which are covered in this Blog:

  • What is XPath?

  • Different ways for writing Xpath

  • Advantages and Disadvantages of Xpath

Let's go step by step.



What is Locator?


First of all, what is the Locator? The locator is the address that identifies a web element uniquely within the webpage.


Locators are the HTML properties of a web element which helps Selenium to find the web element on which it needs to perform the action.


WebElement Interface is an Interface in Selenium. This interface is used to perform all operations while interacting with the webpage. WebElement Interface has all the methods which are mostly required to perform actions on the Webpage such as clear(), click(), sendKeys(), etc.


Also, WebElement represents an individual HTML element.


Different Types of Locators


There are 8 different locators in Selenium namely:


1) By className()


2) By id()


3) By name()


4) By tagName()


5) By linkText()


6) By partialLinkText()


7) By cssSelector


8) By xpath



Out of all these locators, the two Most commonly and frequently used are By cssSelector() and By xpath(). In this blog, we will discuss everything about Xpath.


What is Xpath?


Xpath is used to locate a web element based on its XML path. XML stands for Extensible Mark-up Language and is used to store, organize and transport arbitrary data. It stores data in a key-value pair which is very much similar to HTML tags. Both being the mark-up languages and since they fall under the same umbrella, Xpath can be used to locate HTML elements.

The fundamental behind locating elements using Xpath is the traversing between various elements across the entire page and thus enabling a user to find an element with the reference of another element.


Xpath can be created in two ways:

Absolute Xpath

It is the direct way to find the element.

For example: /html/body/div/div/div/div/div/div/div/form/div/div/div[2]/input[@name='username']

The key characteristic of XPath is that it begins with the single forward slash(/), which means you can select the element from the root node.

The success rate of finding an element using Xpath is almost 100%. Xpath can find relatively all the elements on a web page. Thus, this absolute Xpath can be used to locate elements having no id, class, or name.

But the disadvantage of the absolute XPath is that if there are any changes made in the path of the element then that XPath gets failed.


Relative Xpath

For Relative Xpath the path starts from the middle of the HTML DOM structure. It starts with the double forward slash (//), which means it can search the element anywhere on the webpage.

You can start from the middle of the HTML DOM structure and no need to write a long xpath.


Different ways for writing Xpath

· Creating a valid Xpath is a tricky and complex process.

· While creating Xpath, the user should be aware of the various rules and protocols.


To make the process of writing Xpath simple, lets break it into parts


Firstly let's understand the Most Common terms and symbols are:


  • // : Selects current node.

  • Tagname: Name of the particular node.

  • @: Selects attribute.

  • Attribute: name of the Attribute.

  • Value: Value of the attribute.

Now Let's try to learn to write the Xpath.


Basic XPath

XPath expression selects nodes or a list of nodes based on attributes like ID, Name, ClassName, etc.

Syntax:

//tag[@Attribute='value']

Sample Element: Use the following link and element to practice

https://opensource-demo.orangehrmlive.com/ (username)


Example: //input[@name='username']


Dynamic XPath

Sometimes the value of attributes changes dynamically i.e. they keep on varying. To handle such elements we use Dynamic XPath. Following are the ways we can use to write dynamic Xpaths according to our needs.


contains()

Contains() is a method used in XPath expression. It is used when the value of any attribute changes dynamically. The contain feature can find the element with partial text


Sample Element: https://opensource-demo.orangehrmlive.com/ (Employee name containing 'ta') in Admin module.

Example:

//*[contains(text(),'ta')]


Using or & and

Or

  • In OR expression, two conditions are used, where 1st condition OR 2nd condition should be true.

  • It is also applicable if any one condition is true or maybe both. It means any one condition should be true to find an element.

Syntax : // tagname[@Attribute1='value1' or @Attribute2='value2']


Sample Element: https://opensource-demo.orangehrmlive.com/ (Login Button)

Example:

//button[@type='submit' or @class ='oxd-button oxd-button--medium oxd-button--main orangehrm-login-button']


AND

  • In AND expression, two conditions are used, both conditions should be true to find the element.

  • It fails to find an element if any one condition is false.


Syntax : // tagname[@Attribute1='value1' and @Attribute2='value2']


Sample Element: https://opensource-demo.orangehrmlive.com/ (Login Button)

Example:

//button[@type='submit 'and @class ='oxd-button oxd-button--medium oxd-button--main orangehrm-login-button']

Starts-with function

Start-with function finds the element whose attribute value changes on refresh or any operation on the webpage.

In this expression, match the starting text of the attribute is used to find the element whose attribute changes dynamically.

We can also find the element whose attribute value is static (not changes).


Syntax : // tagname[starts-with(@type,'starting text')]


Sample Element: https://opensource-demo.orangehrmlive.com/ (Login Button)

Example:

// button[starts-with(@type,'sub')]


text()

In this expression, with text function, we find the element with an exact text match as shown below.

Sample Element: https://opensource-demo.orangehrmlive.com/ (Admin Module)


Example: //span[text()='Admin']

Note: .(dot) is also used to read text from the WebElement in place of text().

Example: //span[.='Admin']


not()

not() is used to negate the attribute value.

It is used when the value of any attribute changes dynamically and you may be looking for an attribute value that shall not contain.

This can be used with any conjunction of other axes like not (contains ()) etc.


Sample Element: https://opensource-demo.orangehrmlive.com/ (Password field)


Example:

//input[not(@name='username') and not(@type='hidden')]


As per the above xpath expression, it selects input boxes on a page which does not have the type ‘hidden’ and a name not having a username.


Note: not() expects your expression to be in parenthesis. So not () is always followed by parenthesis.


Following

Selects all elements in the document of the current node ( ).


Sample Element: https://opensource-demo.orangehrmlive.com/ (All the elements of the Menu Bar on the Left side of the Home Page)

Example:

//ul[@class='oxd-main-menu']//following::li[@class='oxd-main-menu-item-wrapper']


We can change the XPath according to the requirement by putting [1],[2]…………and so on.

Example:

(//ul[@class='oxd-main-menu']//following::li[@class='oxd-main-menu-item-wrapper'])[1]


following-sibling

Select the following sibling of the context node.


Sample Element: https://opensource-demo.orangehrmlive.com/ (PIM module on Menu Bar on Left side of Home Page). We can first go to node Admin and then find an immediate sibling which is PIM.


Example:

((//ul[@class='oxd-main-menu']//following::li[@class='oxd-main-menu-item-wrapper'])[1])/following-sibling::li[1]


preceding

Select all nodes that come before the current node.


Sample Element: https://opensource-demo.orangehrmlive.com/ (ADMIN module on Menu Bar on Left side of Home Page). We can first go to node PIN and then finding preceding Node which is PIM.

Example: //li[@class='oxd-main-menu-item-wrapper'][2]/preceding::li


One more

Sample Element: https://opensource-demo.orangehrmlive.com/ (ADMIN module on Menu Bar on Left side of Home Page). We can first go to node Leave (3rd Module) and then find the preceding Node. There are 2 nodes. One is PIM and another is ADMIN.

//li[@class='oxd-main-menu-item-wrapper'][3]/preceding::li

To Go to PIM use [1]

//li[@class='oxd-main-menu-item-wrapper'][3]/preceding::li[1]

To Go to ADMIN use [2]

//li[@class='oxd-main-menu-item-wrapper'][3]/preceding::li[2]



Preceding-sibling

Select sibling nodes that come before the current node.


Sample Element: https://opensource-demo.orangehrmlive.com/ (ADMIN module on Menu Bar on Left side of Home Page). We can first go to node PIN and then find the preceding sibling which is PIM.

Example:

//li[@class='oxd-main-menu-item-wrapper'][2]/preceding-sibling::li


ancestor

The ancestor axes select all ancestors element (grandparent, parent, etc.) of the current node.

Sample Element: https://opensource-demo.orangehrmlive.com/ (All div ancestors before li for Menu bar of module list)

Example: //li[@class='oxd-main-menu-item-wrapper']/ancestor::div


parent

Selects the parent of the current node.

Sample Element: https://opensource-demo.orangehrmlive.com/ (Parent node of username)


Example:

//input[@name='username']//parent::div


Note: ..(dot dot) is also used to refer to the immediate parent of the WebElement


Example: //input[@name='username']/..


self

Selects the current node or 'self' means it indicates the node


Sample Element: https://opensource-demo.orangehrmlive.com/ (Password Field)

Example: //*[@type='password']//self::input


Note: In the above Xpath * represents any element type


child

Selects all children elements of the current node.


Sample Element: https://opensource-demo.orangehrmlive.com/ (All the elements of the Menu Bar on the Left side of the Home Page)

Example: //ul[@class='oxd-main-menu']/child::li


descendant

Selects the descendants of the current node.


Sample Element: https://opensource-demo.orangehrmlive.com/ (All input tags on Login Page)

In the below expression, it identifies all the element descendants to the current element ( div) which means down under the node (child node, grandchild node, etc.).


Example: //div/descendant::input


Note: If multiple elements are selected for any Xpath, you can select the particular element by using its index like [1], [2], etc. Here 1 represents the first element displayed, 2 represents 2nd element displayed, etc. And this can be used with all the above element types.


Normalize-space function

The normalize-space function strips leading and trailing white space from a string replace sequences of whitespace characters with a single space and returns the resulting string. This also removes all new lines and tabs present in a string


Example: //p[normalize-space(text()) = ' (3) Leave Requests to Approve']



These are all the different ways we can write Xpaths.


Advantages and Disadvantages of Xpath


Advantages:


It enables writing compact and easy-to-read queries

Simple Syntax for simple elements

It enables traversing through the DOM forward and backward.


Disadvantages:


The speed of xpath is slower than CSS Selectors

XPath can not resolve some of the web element locating issues


I hope you find this blog about xpath useful.


Thanks and Happy Learning!!

24 views0 comments

Recent Posts

See All
bottom of page