如何选择单选按钮并勾选Box in Selenium
单选按钮 Selenium
单选按钮也可以通过使用 click() 方法来切换。
运用 https://demo.guru99.com/test/radio.html 为了练习,请参见 radio1.click() 切换“Option1”单选按钮。 radio2.click() 切换“Option2”单选按钮,而“Option1”未选中。
如何选择复选框 Selenium
Toggl打开/关闭复选框也可以使用 点击() 方法。
下面的代码将单击 Facebook 的“保持登录状态”复选框两次,然后在打开时输出结果为 TRUE,在关闭时输出结果为 FALSE。
isSelected() 方法用于了解 Checkbox 是打开还是关闭。
这是另一个示例: https://demo.guru99.com/test/radio.html
完整的代码
这是完整的工作代码
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/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 Button1 is selected radio1.click(); System.out.println("Radio Button Option 1 Selected"); //Radio Button1 is de-selected and Radio Button2 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 Check box option1.click(); // Check whether the Check box is toggled on if (option1.isSelected()) { System.out.println("Checkbox is Toggled On"); } else { System.out.println("Checkbox is Toggled Off"); } //Selecting Checkbox and using 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(),则表示 Web 驱动程序访问该页面时未在页面中找到该元素。
- 使用 Firepath 或 Chrome 中的 Inspect Element 再次检查您的定位器。
- 检查您在代码中使用的值是否与 Firepath 中元素的值不同。
- 一些元素的某些属性是动态的。如果您发现值不同且在动态变化,请考虑使用 By.xpath() 或 By.cssSelector(),这些方法更可靠但更复杂。
- 有时,这也可能是一个等待问题,即 Web 驱动程序甚至在页面完全加载之前就执行了您的代码,等等。
- 使用隐式或显式等待在 findElement() 之前添加等待。
总结
- 下表总结了访问上述每种元素类型的命令
元素 | 命令 | 描述 |
---|---|---|
确保 Box, 单选按钮 | 点击() | 用于打开/关闭元素 |