如何判断在 Selenium for Java 中是否选中了复选框?

我使用 Java 中的 来测试 webapp 中的复选框:

private boolean isChecked;
private WebElement e;

我声明 e并将其分配给复选框所在的区域。

isChecked = e.findElement(By.tagName("input")).getAttribute("checked").equals("true");

奇怪的是,getAttribute("checked")返回 null,因此返回 NullPointerException

在复选框的 HTML 中,没有显示 checked属性。但是,所有的 input元素都有一个 checked = "true",所以这段代码应该可以工作,不是吗?

230536 次浏览

The mechanism of selenium framework:

Here selenium make request to the its server and fetch first subelement with tagname input

WebElement e = e.findElement(By.tagName("input"));

Than you try to receive attribute on that element

object attribute = e.getAttribute("checked")

So either use

findElement(By.attribute("checked")

or use

findElement(By.xpath("\\input[@checked='true']")

P.S. I'm not familiar with java's equivalent of selenium api so some method may be named slightly different.

If you are using Webdriver then the item you are looking for is Selected.

Often times in the render of the checkbox doesn't actually apply the attribute checked unless specified.

So what you would look for in Selenium Webdriver is this

isChecked = e.findElement(By.tagName("input")).Selected;

As there is no Selected in WebDriver Java API, the above code should be as follows:

isChecked = e.findElement(By.tagName("input")).isSelected();
 if(checkBox.getAttribute("checked") != null) // if Checked
checkBox.click();                         //to Uncheck it

You can also add an and statement to be sure if checked is true.

I would do it with cssSelector:

// for all checked checkboxes
driver.findElements(By.cssSelector("input:checked[type='checkbox']"));
// for all notchecked checkboxes
driver.findElements(By.cssSelector("input:not(:checked)[type='checkbox']"));

Maybe that also helps ;-)

if ( !driver.findElement(By.id("idOfTheElement")).isSelected() )
{
driver.findElement(By.id("idOfTheElement")).click();
}

For the event where there are multiple check-boxes from which you'd like to select/deselect only a few, the following work with the Chrome Driver (somehow failed for IE Driver):

NOTE: My check-boxes didn't have an ID associated with them, which would be the best way to identify them according to the Documentation. Note the ! sign at the beginning of the statement.

if(!driver.findElement(By.xpath("//input[@type='checkbox' and @name='<name>']")).isSelected())
{
driver.findElement(By.xpath("//input[@type='checkbox' and @name= '<name>']")).click();
}
  1. Declare a variable.
  2. Store the checked property for the radio button.
  3. Have a if condition.

Lets assume

private string isChecked;
private webElement e;
isChecked =e.findElement(By.tagName("input")).getAttribute("checked");
if(isChecked=="true")
{


}
else
{


}

Hope this answer will be help for you. Let me know, if have any clarification in CSharp Selenium web driver.

public boolean getcheckboxvalue(String element)
{
WebElement webElement=driver.findElement(By.xpath(element));
return webElement.isSelected();
}