As we all know, functional testing scripts that run through the UI need stable locators in order to locate the elements.

Selenium uses the following locator strategies:

• ID

• Name

• Class Name

• XPath

• CSS Selector

• Tag Name

• Link Text

• Partial Link Text

But what happens if none of those locators are stable?

What happens if even the ID is dynamic and changes with each rendering of the page?

Let's say you want to click on the Register button, which has the register_312312312 ID.

The classic way to write the Selenium code would be something like this:

But that won't work, because the next time when you run your test and the page is rendered, it will have a different ID.

We could also write a custom CSS Selector, but our purpose here is to find the ID of that element and use it in our test.

We need to grab on to something that makes that element unique, perhaps an attribute.

But we will need to use JavaScript in order to achieve that.

Luckily, Selenium has the execute_script() method for such cases.

As we can see, the Register button has an attribute named title which has the value Register. This is what makes this element unique on that page.

This is the JavaScript code that you would have to execute in order to find that element and get the ID:



We just have to add that JavaScript code into a variable and execute it in our Selenium code:



Notice how I'm returning that variable which contains the ID to a Python variable. After that, I'm clicking on the element by locating it with the ID from that Python variable.

And voilà, we did it!

We are now handling dynamic locators with Selenium WebDriver.

This can also be executed in Endtest:



