简体   繁体   中英

How can I check a checkbox in Selenium WebDriver with Java?

I am using Selenium in Java to test the checking of a checkbox in a web application. Here's my code:

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

But this code returns incorrect value. The checkbox in the HTML:

Active checkbox

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

Inactive checkbox

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

How can I solve this problem in Selenium WebDriver with Java?

You can't use isSelected(), because it is not a standard HTML input element.

My suggested solution is: you can take class attribute and check with active one:

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

The issue is mainly because the checkbox that you have created is not a standard input checkbox element that HTML has, but a custom one. In order to check it, you can perform a click operation on it and see if it works.

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

In order to verify whether it's checked, you can verify the class of the element which adds ui-state-active to the div element when it's active.

Here's how -

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');
}

Or get the class attribute of the element and then use it to see if it exists.

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

I managed to solve it, but it is not a too pretty solution:

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

For more tricky situations:

Checkboxes have a pseudo CSS selector, "checked".

So you can add 'checked' to your CSS selector like this:

let check = !!driver.findElement({css:"div.ui-chkbox-box:checked"});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM