I want to locate an element by its id in my webpage which is a text field where I enter a name. So the element is :
<input type="text" id="a110_name" name="name" maxlength="255">
The first time, my test works well. If I add a loop to click again to the element, selenium does not find because the id has changed.
ex: the id is changing each time I click on it.
<input type="text" id="a110_name" name="name" maxlength="255">
<input type="text" id="a120_name" name="name" maxlength="255">
my code:
driver.findElement(By.id("a110_name")).sendKeys("test");
How can I resolve this problem?
Good to hear that you have solved it using XPATH. You can solve this using CSS locator as below:
driver.findElement(By.cssSelector("input[id$='_name']"));
We have to use XPATH's "contains" keyword with caution, in some cases it might match some other element. If you are more comfortable XPATH, better to use //input[ends-with(@id,'_name')]
Identify Element by containing Text
If the dynamic elements have a definite pattern to them, then we can also use JavaScript functions like “starts-with” or “contains” in our element locators to separate the dynamic part of locator from static part.
For example, in case of Id example which you provided, we can use ‘contains’ function to access this locator irrespective of its dynamic part.
XPath: //input[contains(@id, '_name')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With