使用带有 Java 的 Selenium WebDriver 在组中选择单选按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23424594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select Radio Button in a group using Selenium WebDriver with Java
提问by Mass
I want to be able to select a radio button within a group (of radio buttons) identified by the name attribute:
我希望能够在由 name 属性标识的一组(单选按钮)中选择一个单选按钮:
<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.
问题是 Selenium 总是选择第一个单选按钮,无论option
参数的值是多少。
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
采纳答案by Abhishek Yadav
The code is absolutely working fine for me on Firefox 28. I have tried something like this:
该代码在 Firefox 28 上对我来说绝对工作正常。我尝试过这样的事情:
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);
回答by bit
A simple work around could be using the value
or the id
attributed.
一个简单的解决方法是使用value
或id
属性。
driver.findElement(By.id("optionRadio" + (option + 1))).click();
回答by Raghu Kasturi
Also you can use xpath, something like this:
您也可以使用 xpath,如下所示:
driver.findElement(By.xpath("//input[@value='1]")).click();