Handling Dynamic Web Elements in Selenium WebDriver

TechiesHub9
2 min readDec 8, 2020

Dynamic Web Elements are those elements whose Id, Class, Name, CSS -attribute etc. keep changing through every page refresh.
These are database based elements and its values get refreshed every-time the database gets updated.

Relative XPath is the preferred method for handling Dynamic web elements in Selenium WebDriver.
The relative Xpath can find Dynamic Web-Elements utilizing a partial pattern match.

A Partial Pattern match locates a WebElement based on part of the value.

Partial Pattern Match Types –

1. starts-with
2. ends-with
3. contains

There are different ways through which we can handle dynamic elements.
1. Absolute XPath
2. Relative XPath — Partial Pattern Match
3. Index
4. Using Multiple Attribute

1. Using Absolute XPath –

Absolute Xpath is the path starting from the root tag.
For ex. — /html/body/nav/div[1]/input[1]

Here the problem is, if something changes in the structure of your web page, your code will break.
So this is not a recommended way to handle Dynamic Web Elements.

2. Using Relative XPath –

Relative XPath is the preferred method for handling Dynamic Web Elements.It can be handle by using starts-with, ends-with, contains attributes.

Consider an example –

<input type=”submit” id=”01_Save” value=”Save”>

This saves button on the page has an id with a dynamically changing number in it.

It changes on every page reload. It always contains Save word.

It can be identified as — //input[contains(@id, ‘Save’)

3. Using Index –

Many times you will face that the different elements with same locator value. At such time you can select the element by using a level index.
For ex. If any form contains 10 submit buttons and you want to choose 7th button, then you can find it by index.

4. Using Multiple Attributes –

We can use multiple conditions to search an element using XPath.Sometimes it’s not possible to find WebElement by using one attribute so at that place, we can use more than one attribute like –

For ex. If any tag contains id=’type’ and name=’Save’ then Xpath- //input[starts-with(@id,’type’) and contains(@name,’Save’)]

5. Using stable preceding, Following Node –

Following node contains all nodes that follow the context node. We can apply ‘following’ to specify the following elements in the web element list. — Preceding node contains all nodes that precede the context node. It is opposite to following.

This approach might not be possible in all scenarios but it does resolve the dynamic element issue in some cases.
Ex. — //div[@id=’xx’]//following::input
//tagName[@attribute=value]//preceeding::tagName
These are some ways to find Dynamic Web Elements.

Check the link for more updates.

--

--