如何使用 Selenium Java WebDriver 选择复选框? [英] How can I select checkboxes using the Selenium Java WebDriver?

查看:19
本文介绍了如何使用 Selenium Java WebDriver 选择复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 id 或 XPath 表达式检查复选框?有没有类似于 select by visibletext for a dropdown 的方法?

How can I check the checkboxes using an id or XPath expression? Is there a method similar to select by visibletext for a dropdown?

通过所有其他相关问题的示例,我找不到一个合适的解决方案,它以简洁的方式工作,我可以通过几行或方法检查一个复选框或单选按钮.

Going through the examples given for all other related questions, I could not find a proper solution that works in a concise way that by few line or method I can check a chekbox or radio button.

示例 HTML 部分如下:

A sample HTML section is below:

<tbody>
    <tr>
        <td>
            <span class="120927">
            <input id="ctl00_CM_ctl01_chkOptions_0" type="checkbox" name="ctl00$CM$ctl01$chkOptions$0"/>
            <label for="ctl00_CM_ctl01_chkOptions_0">housingmoves</label>
            </span>
        </td>
    </tr>

    <tr>
        <td>
            <span class="120928">
            <input id="ctl00_CM_ctl01_chkOptions_1" type="checkbox" name="ctl00$CM$ctl01$chkOptions$1"/>
            <label for="ctl00_CM_ctl01_chkOptions_1">Seaside & Country Homes</label>
            </span>
        </td>
    </tr>
</tbody>

推荐答案

选择复选框类似于单击按钮.

Selecting a checkbox is similar to clicking a button.

driver.findElement(By.id("idOfTheElement")).click();

会做的.

但是,您也可以查看复选框是否已被选中.以下代码段检查复选框是否被选中.如果未选中,则选中.

However, you can also see whether the checkbox is already checked. The following snippet checks whether the checkbox is selected or not. If it is not selected, then it selects.

if ( !driver.findElement(By.id("idOfTheElement")).isSelected() )
{
     driver.findElement(By.id("idOfTheElement")).click();
}

这篇关于如何使用 Selenium Java WebDriver 选择复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆