Webdriver 检查复选框是否已设置,如果未设置则设置

软件测试 自动化测试 网络驱动程序 硒2 朱尼特
2022-01-11 19:51:45

我通过阅读 Alan Richardson 的Selenium Simplified书并将练习/测试从 Selenium RC 转换为 Webdriver 来学习 JUnit 的 Webdriver。到目前为止,这已被证明是一次极好的学习体验。但是最近我遇到了一个问题,尽管进行了广泛的搜索,但仍然无法解决。

在 Selenium RC 中有一个selenium.check命令,如果它是空的,它将检查一个框,如果它已经被选中,则离开它。例如:

selenium.check("//input[@name=’checkboxes[]’ and @value=’cb3’]");

如果您访问目标网站 ( http://compendiumdev.co.uk/selenium/basic_html_form.html ),您将看到三个复选框,其中一个被选中。我写了一些伪代码,但无法让它工作。这是伪代码:

isChecked = driver.findElement(By.xpath("//input[@type='checkbox']"));

if (isChecked = false) {
    check the box;
} else {
    do nothing;
}

我知道布尔值isSelected()应该具有特色,但我不知道在哪里可以超越。我所有的研究都返回了部分解决方案,但没有任何东西足够接近让我对解决方案充满信心。

4个回答

在 Selenium Simplified 课程中,选择器的秘密实际上是“值”而不是“类型”,因为“值”在该页面上唯一标识 WebElement,并加上“以防万一”类型

WebElement checkBox1;
WebElement checkBox3;

checkBox1 = driver.findElement(By.cssSelector("input[value='cb1']"));
checkBox3 = driver.findElement(By.cssSelector("input[value='cb3']"));

if(!checkBox1.isSelected()){
    checkBox1.click();
}

//checkBox3 is selected by default
if(checkBox3.isSelected()){
    checkBox3.click();
}

或者使用findElements代码。

你可以改为:

List<WebElement> selectElements= 
driver.findElements(By.cssSelector("input[name='checkboxes[]']"));

selectElements.get(0).click();

if( selectElements.get(2).isSelected()){
    selectElements.get(2).click();
}

或遍历它们:

for(WebElement checkbox : selectElements){
    // uncheck 'em all
    if(checkbox.isSelected()){
      checkbox.click();
    }
}

希望有帮助。

它应该很简单:

IWebElement element = driver.findElement(By.xpath("//input[@type='checkbox']"));
if (!element.Selected)
{
    element.Click();
}

在 C# 中非常简单

例子 :

IWebElement chkBox = driver.FindElement(By.Id("some id "));
if (chkBox.Selected) {
  //perform actions 
} else {
  //perform actions
}

这是一个工作代码示例 - 通过男性和女性单选按钮选择性别。

/* load that webelement list of radio buttons. then follow the below code & logic */
List<WebElement> rdBtn_Sex = driver.findElements(By.name("sex"));

// Create a boolean variable which will hold the value (True/False)
boolean bValue = false;

// This statement will return True, in case of first Radio button is selected
bValue = rdBtn_Sex.get(0).isSelected();

// This will check that if the bValue is True means if the first radio button is selected
if (bValue = true) {
     // This will select Second radio button, if the first radio button is selected by default
    rdBtn_Sex.get(1).click();
} else {
     // If the first radio button is not selected by default, the first will be selected
     rdBtn_Sex.get(0)).click();
}