选择单选按钮并检查Box in Selenium
⚡ 智能摘要
选择单选按钮并检查Box in Selenium 本教程涵盖了使用 WebDriver 自动化两种最常用表单控件的技术。教程解释了如何使用 click() 和 isSelected() 方法切换单选按钮和复选框,并逐步演示了具体的操作步骤。 Java 代码,并分享脆弱定位器的故障排除技巧。

单选按钮 Selenium
单选按钮通过以下方式切换开启/关闭: click() 方法,就像任何其他 WebElement 一样 Selenium由于单选按钮组中一次只能激活一个选项,因此单击第二个选项会自动取消选择第一个选项。
运用 https://demo.guru99.com/test/radio.html 作为练习页面,请注意: radio1.click() 选择“选项1”单选按钮。呼叫 radio2.click() 然后选择“选项2”,同时保持“选项1”未选择。
如何选中复选框 Selenium
Toggl启用或禁用复选框也是使用以下方式完成的: click() 方法。下面的代码会点击 Facebook 的“保持登录状态”复选框两次,并在选中复选框时输出 TRUE,取消选中复选框时输出 FALSE。
此 isSelected() 该方法用于确认复选框是否处于打开或关闭状态——这是在测试用例中验证表单状态时的一个关键断言。
以下是另一个示例页面: https://demo.guru99.com/test/radio.html.
完成: Code 例如:
以下是完整的可运行代码,用于切换单选按钮和 Facebook 持久登录复选框。
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.*;
public class Form {
public static void main(String[] args) {
// Declaration and instantiation of objects and variables
System.setProperty("webdriver.chrome.driver", "G:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://demo.guru99.com/test/radio.html");
WebElement radio1 = driver.findElement(By.id("vfb-7-1"));
WebElement radio2 = driver.findElement(By.id("vfb-7-2"));
// Radio Button 1 is selected
radio1.click();
System.out.println("Radio Button Option 1 Selected");
// Radio Button 1 is de-selected and Radio Button 2 is selected
radio2.click();
System.out.println("Radio Button Option 2 Selected");
// Selecting Checkbox
WebElement option1 = driver.findElement(By.id("vfb-6-0"));
// This will toggle the checkbox
option1.click();
// Check whether the checkbox is toggled on
if (option1.isSelected()) {
System.out.println("Checkbox is Toggled On");
} else {
System.out.println("Checkbox is Toggled Off");
}
// Selecting a Checkbox and using the isSelected method
driver.get("https://demo.guru99.com/test/facebook.html");
WebElement chkFBPersist = driver.findElement(By.id("persist_box"));
for (int i = 0; i < 2; i++) {
chkFBPersist.click();
System.out.println("Facebook Persists Checkbox Status is - " + chkFBPersist.isSelected());
}
// driver.close();
}
}
故障排除
如果遇到 NoSuchElementException 找不到元素意味着 WebDriver 访问页面时该元素不存在。请使用以下清单快速恢复:
- 使用 FirePath 或 Chrome 中的“检查元素”功能再次检查您的定位器。
- 确认代码中使用的值与页面上元素的当前值一致。
- 有些元素具有动态属性,类似于您在以下情况下可能看到的情况: 在下拉菜单中选择一个 Selenium 网络驱动程序在这种情况下,最好选择
By.xpath()orBy.cssSelector()它们更可靠,但稍微复杂一些。 - 有时问题出在时机上——WebDriver 在页面加载完成之前就执行了你的代码。
- 添加等待时间
findElement()使用隐式或显式等待,给元素时间进行渲染。




