简体   繁体   English

如何在Java中使用Selenium WebDriver从多个选择框中选择一个复选框?

[英]How to select a checkbox from a multiple select box using selenium webdriver in java?

I have the below code for the multiple select box in the web page and I need to make a selection of any option group for the list using selenium webdriver 我在网页中具有以下用于多重选择框的代码,我需要使用Selenium Webdriver为列表选择任何选项组

<div class="ms-drop bottom" style="display: block;">
    <div class="ms-search">
        <ul style="max-height: 250px;">
            <li class="group">
                <label class="optgroup" data-group="group_0" style="display: block;">
                    <input type="checkbox" name="selectGroup">AmaWaterways
                </label>
            </li>
            <li class="multiple" style="width: 180px;">
                <label style="display: block;">
                    <input type="checkbox" data-group="group_0" value="AmaSerena" name="selectItem">AmaSerena
                </label>
            </li>
            <li class="multiple" style="width: 180px;">
                <label style="display: block;">
                    <input type="checkbox" data-group="group_0" value="AmaPura" name="selectItem">AmaPura
                </label>
            </li>
        </ul>
    </div>
</div>

Can somebody suggest how to select an option group of my choice? 有人可以建议如何选择我选择的选项组吗?

In order to toggle a checkbox, it is as simple as clicking it. 为了切换一个复选框,就像单击它一样简单。

String targetOption = "whatever";
By targetOptionLocator = By.cssSelector("input[type=checkbox][value=" + targetOption + "]");
driver.findElement(targetOptionLocator).click();

You may also want to check if a checkbox is already checked: WebElement#isSelected . 您可能还希望检查是否已选中一个复选框: WebElement#isSelected

Eg: 例如:

void selectOption(String optionName) {
  By targetOptionLocator = By.cssSelector("input[type=checkbox][value='" +  + optionName + "']");
  WebElement option = driver.findElement(targetOptionLocator);
  if(!option.isSelected())
    option.click();
}

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

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