I want to be able to select a radio button within a group (of radio buttons) identified by the name attribute:
<div>
<input type="radio" name="exampleInputRadio" id="optionRadio1" value="1">
<input type="radio" name="exampleInputRadio" id="optionRadio2" value="2">
<input type="radio" name="exampleInputRadio" id="optionRadio3" value="3">
<input type="radio" name="exampleInputRadio" id="optionRadio4" value="4">
</div>
I use the following code to do what I want:
public void exampleInputRadio(WebDriver driver, int option) {
List<WebElement> radios = driver.findElements(By.name("exampleInputRadio"));
if (option > 0 && option <= radios.size()) {
radios.get(option - 1).click();
} else {
throw new NotFoundException("option " + option + " not found");
}
}
The problem is that Selenium always selects the first radio button, no matter the value of option
argument is.
And when I code this in the above method:
for (int i = 0; i < radios.size(); i++) {
System.out.println(radios.get(i).getAttribute("id"));
}
I get this output:
optionRadio1
optionRadio2
optionRadio3
optionRadio4
一个简单的解决方法是使用value
或id
属性。
driver.findElement(By.id("optionRadio" + (option + 1))).click();
The code is absolutely working fine for me on Firefox 28. I have tried something like this:
function:
public void exampleInputRadio(WebDriver driver, int option) {
List<WebElement> radios = driver.findElements(By.name("exampleInputRadio"));
if (option > 0 && option <= radios.size()) {
radios.get(option - 1).click();
} else {
throw new NotFoundException("option " + option + " not found");
}
}
functions called:
TestClass tc = new TestClass();
tc.exampleInputRadio(driver, 1);
tc.exampleInputRadio(driver, 2);
tc.exampleInputRadio(driver, 3);
tc.exampleInputRadio(driver, 4);
您也可以使用xpath,如下所示:
driver.findElement(By.xpath("//input[@value='1]")).click();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.