1

How do I locate the input element by id where the last 2 numerical digits change randomly?

<input id="start-time-hours-c31" class="focused" name="startTimeHours" value="" placeholder="hh" maxlength="2" type="text">
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Scope
  • 49
  • 7

6 Answers6

4

Quick answer

When last 2 numerical digits change randomly,

driver.findElement(By.xpath("//input[contains(@id,'start-time-hours-c')]"));

Using 2 attributes of Input tag,

driver.findElement(By.xpath("//input[@name='startTimeHours' and @class='focused']"));

Please let us know if it resolved your query.

NarendraR
  • 7,577
  • 10
  • 44
  • 82
TheSociety
  • 1,936
  • 2
  • 8
  • 20
3

As the last 2 characters of the id attribute changes randomly, additionally you need to consider some other attributes as well and you can use either of the following Locator Strategies:

  • cssSelector:

    WebElement elem = driver.findElement(By.cssSelector("input[id^='start-time-hours-c'][name='startTimeHours']"));
    
  • xpath:

    WebElement elem = driver.findElement(By.xpath("//input[starts-with(@id, 'start-time-hours-c') and @name='startTimeHours']"));
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
1

As the html also has a name tag you can find the element by using that name tag, like:

WebElement element = driver.findElement(By.name("startTimeHours"));

And if the name tag startTimeHours is not unique on the page, then you can find the element by using the below xpath:

WebElement element = driver.findElement(By.xpath("//input[contains(@id,'start-time-hours')]"));
Sameer Arora
  • 4,439
  • 3
  • 10
  • 20
1

Agreed with @TheSociety answer, you can also be used as the combination of name and id

//input[contains(@id,'start-time-hours-c') and contains(@name,'startTimeHours')]
iamsankalp89
  • 4,607
  • 2
  • 15
  • 36
1

Use contains, sibling or Ancestor when the value is dynamic.

xpath - //input[contsins(@id,'start-time-hours-c')]

Adarsh J
  • 61
  • 6
1

You can use either of them:

 //input[starts-with(@id,'start-time-hours-c')]

(or)

 //input[contains(@id,'start-time-hours-c')]

if the above returns a single webelement then you can use it or else if it returns multiple elements go for name attribute in the xpath.

Fury
  • 142
  • 1
  • 12