user3003560
user3003560

Reputation: 1

Handling dynamic ids and classes

I am using selenium to test a web application, The ids and classes are always changing dynamically.So that I am not able to give correct identification, is it possible to get ids of the element in run time and is there any other method to handle this situation.

Upvotes: 0

Views: 146

Answers (2)

James Dunn
James Dunn

Reputation: 8264

I would strongly recommend locating elements by XPath -- with the caveat that you make your XPaths robust and not just "copy" the xpath using your browser's developer tools. XPath is very easy to learn. You can use XPaths to walk up and down the DOM, and identify elements by their text, or their attributes.

For example, maybe you need to click a button that has a span that contains the text that appears on the button:

<div class="btn-row random-generated-number-1234897395">
...

<button id="random-generated-number-239487340924257">
    <span>Click Here!</span>
</button>

...
</div>

You could then use an xpath like this:

//div[contains(@class, 'btn-row')]//button/span[text()='Click Here!']/..

(The /.. at the end walks back up from the span to the button.)

XPath is powerful and flexible and easy to learn. Use it when the ids and classes aren't reliable.

Upvotes: 0

Petr Mensik
Petr Mensik

Reputation: 27496

It depends on if ids are completely random or if there is some part of the id which remains the same. If yes, then cssSelector is the obvious choice

driver.findElement(By.cssSelector("div[id*=somePart]");

where id* means id contains. If you cant use this approach you will have to track down your element using xpath or again cssSelectors. XPath example is here and CSS selector could look like this

By.cssSelector("boyd table input");

Upvotes: 1

Related Questions