【问题标题】:How to click on multiple checkboxes in selenium webdriver?如何单击 selenium webdriver 中的多个复选框?
【发布时间】:2018-11-14 21:46:41
【问题描述】:

我正在尝试通过从Excel 读取数据来检查表中的多个复选框,它实际上能够从 excel 中读取数据并找到复选框,但它不会选中/单击复选框。正在进行的PrecuationsChk.click();不起作用并且它没有显示任何异常(跳过该行的执行),有人可以向我解释为什么它没有检查/单击复选框吗?下面是我的html代码:

<table id="ContentPlaceHolder1_ctl04_cbl_CCPOP01_01">
  <tbody>
    <tr>
     <td>
    <input id="ContentPlaceHolder1_ctl04_cbl_CCPOP01_01_0"
 type="checkbox"
     name="ctl00$ContentPlaceHolder1$ctl04$cbl_CCPOP01_01$0" 
value=" Universal    ">
<label for="ContentPlaceHolder1_ctl04_cbl_CCPOP01_01_0"> Universal   </label></td>
<td><input id="ContentPlaceHolder1_ctl04_cbl_CCPOP01_01_1" 
type="checkbox" 
name="ctl00$ContentPlaceHolder1$ctl04$cbl_CCPOP01_01$1"
 value=" Aspiration  ">
<label for="ContentPlaceHolder1_ctl04_cbl_CCPOP01_01_1"> Aspiration  </label></td>
    <td><input id="ContentPlaceHolder1_ctl04_cbl_CCPOP01_01_2" 
type="checkbox" name="ctl00$ContentPlaceHolder1$ctl04$cbl_CCPOP01_01$2" 
value=" Respiratory ">
<label for="ContentPlaceHolder1_ctl04_cbl_CCPOP01_01_2"> Respiratory </label></td>
    </tr>
    </tbody>

我已经尝试了以下代码:

String valueOngoingPrecuations = data.getOngoingPrecuations().get(rowCnt);//data reading from excel(Aspiration,Universal)
            List<WebElement> ongoingPrecuations = driver.findElements(By.xpath("//input[@type='checkbox']"));
            List<String> ongoingPrecuationsList = new ArrayList<String>(
                    Arrays.asList(valueOngoingPrecuations.split(",")));
            for (String ongoingPrecuationsCheck : ongoingPrecuationsList) {
                for (WebElement ongoingPrecuationsChk : ongoingPrecuations) {
                    if (ongoingPrecuationsChk.getAttribute("value").equalsIgnoreCase(ongoingPrecuationsCheck)) {
                        ongoingPrecuationsChk.click();

                    }
                }
            }

【问题讨论】:

  • 如果该行被跳过,if 中的条件为 false。调试它,检查值是否真的相等(包括空格)。
  • 使用像 //tbody//input 这样的 xpath,这将为您提供复选框输入数组。
  • 我可以找到网页元素但无法点击复选框
  • 对不起,我没有检查问题描述。请看下面的答案。谢谢
  • 您能否提供更多信息作为 1) 如果您尝试单击所有 &lt;td&gt;(复选框)元素? 2)如果&lt;table&gt; 只包含这3 个&lt;td&gt; 元素? 3)如果&lt;td&gt;(复选框)元素的数量和List&lt;String&gt; ongoingPrecuationsList中的元素数量相同? 4)如果&lt;td&gt;(复选框)元素的数量和List&lt;String&gt; ongoingPrecuationsList中的元素数量不同?

标签: java selenium-webdriver


【解决方案1】:

使用基于 tbody id 的 xpath,如下所示。

//tbody[contains(@id,'tableBodyId')]//input

这将为您提供复选框列表。然后使用

WebElement btn = driver.findElement(By.xpath("xpath"));

btn.click();

【讨论】:

  • 我在同一个网页中有多个带有多个复选框的表格。因此无法使用 xpath("//tbody[contains(@id,'tableBodyId')]");
  • 同意,但是每个标签的 id 都是唯一的,所以用你的 tbody id 替换 tableBodyId 文本。
  • 使用 xpath :- //table[contains(@id,'ContentPlaceHolder')]//输入
猜你喜欢
  • 2018-04-24
  • 2015-12-03
  • 2015-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-07
  • 2017-03-31
相关资源
最近更新 更多