
该文章主要讲解如何识别复选框CheckBox和单选按钮RadioButton
单选按钮也可以通过Click()方法打开
使用网页http://demo.guru99.com/test/radio.html作为练习,如下: 使用radio1.click() 切换到Option1单选按钮; 使用radio2.click() 切换到Option2单选按钮,取消选中Option1 ; 代码如下图所示:

在这里插入图片描述
使用click()方法切换复选框的状态:开/关。 如下的代码是使用账户名和密码登陆百度网址,其中可见到下次自动登陆的复选框。

在这里插入图片描述
WebElement memberPass1; 
memberPass1 = driver.findElement(By.xpath("//*[@id='TANGRAM__PSP_10__memberPass']"));
memberPass.click();
System.out.println("是否选中:" + memberPass.isSelected());
其输出为:"是否选中:False"
isSelected() 方法的作用是:判断复选框是否被勾选。
这里有另外一个例子:Demo主页http://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) {                                    
        // 对象/变量的声明和实例化
        System.setProperty("webdriver.chrome.driver","G:\\chromedriver.exe");                   
        WebDriver driver = new ChromeDriver();                    
        driver.get("http://demo.guru99.com/test/radio.html");                    
        WebElement radio1 = driver.findElement(By.id("vfb-7-1"));                            
        WebElement radio2 = driver.findElement(By.id("vfb-7-2"));                            
        //选择单选按钮Option1    
        radio1.click();            
        System.out.println("Radio Button Option 1 Selected");                    
        //Button1未被选中,Button2被选中        
        radio2.click();            
        System.out.println("Radio Button Option 2 Selected");                    
        // 选择复选框    
        WebElement option1 = driver.findElement(By.id("vfb-6-0"));                            
        // 这将切换复选框
        option1.click();            
        // 检查复选框是否已被选中         
        if (option1.isSelected()) {                    
            System.out.println("Checkbox is Toggled On");                    
        } else {            
            System.out.println("Checkbox is Toggled Off");                    
        }        
        //选择复选框并使用isSelected方法
        driver.get("http://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访问该页面时,该元素不在页面中。
下表总结了访问上面讨论的每种类型元素的命令:
| Element | 命令 | 描述 | 
|---|---|---|
| Check Box, Radio Button | click() | 用于切换元素是否选中 |