如何在Java中查看Selenium Webdriver中的复选框?

时间:2015-09-25 08:41:25

标签: java selenium checkbox selenium-webdriver

我在Java中使用Selenium来测试webapp中复选框的检查。这是我的代码:

<div class="ui-chkbox-box ui-widget ui-corner-all ui-state-default ui-state-active">
<span class="ui-chkbox-icon ui-icon ui-icon-check ui-c"></span>
</div>

但是这段代码返回的值不正确。 HTML中的复选框:

有效复选框

<div class="ui-chkbox-box ui-widget ui-corner-all ui-state-default">
<span class="ui-chkbox-icon ui-icon ui-c ui-icon-blank"></span>
</div>

非活动复选框

{{1}}

如何使用Java在Selenium WebDriver中解决此问题?将不胜感激任何帮助。

4 个答案:

答案 0 :(得分:2)

你不能使用isSelected()因为它不是一个标准的html输入元素。 我建议的解决方案是:你可以使用class属性并检查有效的属性:

if(driver.findElement((By.xpath(xpath1))).getAttribute('class') == 'ui-chkbox-box ui-widget ui-corner-all ui-state-default ui-state-active')
  return True
else
  return False

答案 1 :(得分:1)

问题主要是因为您创建的复选框不是html具有的标准输入复选框元素,而是自定义复选框元素。为了进行检查,您可以对其执行单击操作,看它是否有效。

driver.findElement(By.cssSelector('div.ui-chkbox-box)).click(); //check the checkbox

为了验证是否检查了它,您可以验证在活动时将ui-state-active添加到div元素的元素的类。这是怎样的 -

try{
    driver.findElement(By.cssSelector('div.ui-state-active')); //find the element using the class name to see if it exists
}
catch(NoSuchElementException e){
    System.out.println('Element is not checked');
}

或者获取元素的class属性,然后使用它来查看它是否存在。

driver.findElement(By.cssSelector('div.ui-chkbox-box')).getAttribute('class');

希望它有所帮助。

答案 2 :(得分:1)

我设法解决了,但这不是太漂亮的解决方案:

String a = driver.findElement((By.xpath(xpath1))).getAttribute("class");
System.out.print(a.contains("ui-state-active"));

答案 3 :(得分:0)

对于更棘手的情况      复选框具有sudo css选择器“已选中” 因此,您可以做的就是像这样

将选中的内容添加到CSS选择器中
let check = !!driver.findElement({css:"div.ui-chkbox-box:checked"});