如何使用 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();
}