該文章主要講解如何識別複選框CheckBox和單選按鈕RadioButton
單選按鈕RadioButton
單選按鈕也可以通過Click()方法打開
使用網頁http://demo.guru99.com/test/radio.html作爲練習,如下:
使用radio1.click() 切換到Option1單選按鈕;
使用radio2.click() 切換到Option2單選按鈕,取消選中Option1 ;
代碼如下圖所示:
複選框CheckBox
使用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訪問該頁面時,該元素不在頁面中。
- 使用FireFox中的Firepath或Chrome中的InspectElement(F12)檢查定位元素;
- 檢查代碼中使用的值與Firepath中元素的值是否相同;
- 有些元素的屬性動態的;如果發現值不同,並且動態變化,可以考慮使用By.xpath()或By.cssSelector(),這兩種方法更可靠,但語法結構更復雜一點;
- 另外,還有可能是等待問題,WebDriver甚至在頁面完全加載之前就執行了代碼,所以找不到元素,等等。
- 使用隱式或顯式等待,在查找定位元素之前;等待詳情請參考文章:5-Selenium WebDriver三種等待–隱式等待-顯式等待和流暢等待
下表總結了訪問上面討論的每種類型元素的命令:
Element | 命令 | 描述 |
---|---|---|
Check Box, Radio Button | click() | 用於切換元素是否選中 |