Dealing with Dynamic Locators
Introduction
Some frameworks will generate elements with dynamic locators, which will have a different ID with each rendering of the page.
For example, a button might have the ID register_325629
and might have the ID register_861951
after reloading the page.
Solutions
1. Change the Settings for the Endtest Chrome Extension
The Endtest Chrome Extension has a Settings
section where you can configure it to not use the ID attribute.
You can update those settings even after the recording has started.
If your elements have custom data attributes, you can take advantage of that and add the name of those attributes in the Custom data attributes
textarea from the Settings
section.
2. Write a custom XPath
The element might have a certain attribute that has a certain value that doesn't change over time.
You can write an XPath which locates the element by using that attribute, like this:
//*[@attribute = "attribute_value"]
You can also write an XPath which locates the element by using only part of the value of the attribute:
//*[contains(@attribute, "part_of_attribute_value")]
And you can also write an XPath which uses multiple attributes:
//*[@attribute_1 = "attribute_value_1" and @attribute_2 = "attribute_value_2" ]
3. Write a custom CSS Selector
The element might have a certain attribute that has a certain value that doesn't change over time.
You can write a CSS Selector which locates the element by using that attribute, like this:
[attribute='attribute_value']
But what if we actually need to find out what that ID is?
In order to tackle this situation, we have to use the Execute JavaScript
action and locate the element by using one its attributes.
If the element has the title
attribute with the value Register
, we need to run the following JavaScript code with the Execute JavaScript
action:
theId = document.querySelector("*[title='Register']").getAttribute("id");
After that, we can just transfer the value from that JavaScript variable to an Endtest variable with the Extract Value from JS Variable
option from the Set Variable
action.
More details about writing custom XPaths and CSS Selectors are available in the Finding elements in Web Applications chapter.