简体   繁体   English

使用带有Java的Selenium WebDriver在组中选择单选按钮

[英]Select Radio Button in a group using Selenium WebDriver with Java

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

一个简单的解决方法是使用valueid属性。

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: 该代码对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);

您也可以使用xpath,如下所示:

driver.findElement(By.xpath("//input[@value='1]")).click();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM