2015-09-25 111 views
0

我在Java中使用Selenium来测试webapp中复选框的检查。以下是我的代码:如何在Java中使用Selenium Webdriver检查复选框?

boolean isChecked = driver.findElement((By.xpath(xpath1))).isSelected(); 

但是,此代码返回不正确的值。在HTML复选框:

活动复选框

<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> 

活动状态复选框

<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> 

我怎样才能在硒的webdriver解决这个问题与Java?将不胜感激任何帮助。

回答

2

你不能使用isSelected(),因为它不是一个标准html输入元素。 我建议的解决办法是:你可以采取类属性,并与活跃之一查询:

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

问题主要是因为您创建的复选框不是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'); 
} 

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

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

希望它有帮助。

+0

在页面已超过10复选框相同的属性。 – Milky

1

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

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