2

In my case, there are some legacy web sites, in which not all the inputs have id attribute properly set. Such as this:

<div class="form-group">
    <label>Amount</label>
    <input id="unreasonablename" type="text" value=""></input>
</div>

But human testers can still test it by typing amount value in the input right behind "Amount". I'd like to make web driver do the same thing:

webDriver.inputAfter("Amount", 100); //I do not want to use "unreasonablename" to find the input.

But how can I find the input element after the text "Amount"? Thanks.

There is a relative question here: In Selenium Webdriver, how to get a text after an element?. But I'm not familiar with xpath and do not know if my case can be solved in the same way.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
cheny
  • 2,545
  • 1
  • 24
  • 30

4 Answers4

3

To find the <input> element just after the text Amount you can use the findElement() method along with the Locator Strategy as follows :

webDriver.findElement(By.xpath("//label[contains(.,'Amount')]//following::input[1]"));
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
2

you can try following_sibling as

webDriver.findElement(By.xpath("//*[text()='Amount']/following-sibling::Input"));
Vin
  • 165
  • 2
  • 12
2

try this :

driver.findElement(By.xpath("//label[text()='Amount']/following-sibling::input")).sendKeys("amount to be sent");
cruisepandey
  • 28,520
  • 6
  • 20
  • 38
1

you can write some generic method like below. It can be used for all the required fileds by passing the label name and input value as argument

void enterInputAfterLabel(String labelname,String value){
driver.findElement(By.xpath("//label[text()='"+labelname+"']]/input")).sendKeys(value);
}
Subburaj
  • 2,294
  • 3
  • 20
  • 37