在selenium webdriver中获取没有Name或Xpath的选中复选框

时间:2016-03-21 10:47:15

标签: angularjs selenium xpath selenium-webdriver

如何从没有名称或xpath的复选框列表中获取所选的复选框

复选框图片enter image description here

  

生成HTML代码

<div class="checkbox ng-scope" ng-repeat="item in options track by $index">
   <label class="ng-binding" style="float:left;">
<input type="checkbox" class="ng-pristine ng-valid" ng-change="textfieldKeypress(onkeypress)" ng-model="$parent.inputArray[$index]" validator="[onwatch,onblur]" value="item" >
    Ache </label> 
</div>

这是我曾经尝试过但不是正确的方法,因为有多个没有名字的复选框列表

List<WebElement> CheckBoxList = driver.findElements(By.tagName("checkbox"));
    for (int i = 0; i < CheckBoxList.size(); i++) {
        if (CheckBoxList.get(i).isSelected()) {
            Assert.assertEquals("Ache", CheckBoxList.get(i).getText());
        }
    }

3 个答案:

答案 0 :(得分:1)

尝试使用以下xpath = //div[@class='checkbox ng-scope']

如果你有一个复选框,那么请使用xpath

下方

(// div[@class='checkbox ng-scope']) [1]您将值1更改为2/3/4,依此类推。

答案 1 :(得分:1)

而不是使用isSelected()使用.getAttribute("checked"),然后在if子句中将返回值与布尔值true进行比较。

答案 2 :(得分:-1)

由于无法使用XPath评估复选框状态,并且无法使用CSS选择器评估文本,因此我将采用两者中存在的元素:

// get the checked checkboxes
List<WebElement> m_checked = driver.findElements(By.cssSelector("input:checked[type=checkbox]"));

// get the checkboxes matching the text
List<WebElement> m_text = driver.findElements(By.xpath("//label[normalize-space(.)='Ache']/input[@type='checkbox']"));

// get the checkboxes checked matching the text
Collection elements = CollectionUtils.retainAll(m_checked, m_text);