本文系統整理 Selenium WebDriver 對常見網頁元素的定位與操作 API,包含連結、文字輸入框、按鈕、下拉選單、單選鈕與核取方塊,附完整程式碼範例,適合自動化測試入門參考。
<div> <p>連結 link</p> <a href="www.cnblogs.com/tankxiao">小坦克</a> </div>
// 完整連結文字定位
WebElement link1 = driver.findElement(By.linkText("小坦克"));
// 部分鏈結文字定位
WebElement link11 = driver.findElement(By.partialLinkText("坦克"));
// 點擊操作
link1.click();
<div> <p>輸入框 textbox</p> <input type="text" id="usernameid" value="username" /> </div>
WebElement element = driver.findElement(By.id("usernameid"));
// 輸入文字
element.sendKeys("test111111");
// 清空輸入框
element.clear();
// 取得目前數值
String value = element.getAttribute("value");
<div> <p>按鈕 button</p> <input type="button" value="新增" id="proAddItem_0" /> </div>
// 使用 XPath 定位 String xpath = "//input[@value='新增']"; WebElement addButton = driver.findElement(By.xpath(xpath)); // 點擊 addButton.click(); // 判斷是否啟用 boolean enabled = addButton.isEnabled();
<select id="proAddItem_kind" name="kind"> <option value="1">電腦硬體</option> <option value="2">房產</option> <option value="18">類別AA</option> <option value="19">類別BB</option> <option value="20">類別BB</option> <option value="21">類別CC</option> </select>
Select select = new Select(driver.findElement(By.id("proAddItem_kind")));
// 依索引選擇 (從 0 開始)
select.selectByIndex(2);
// 依 value 選擇
select.selectByValue("18");
// 依可見文字選擇
select.selectByVisibleText("類別AA");
// 取得所有選項
List<WebElement> options = select.getOptions();
for (WebElement option : options) {
System.out.println(option.getText());
}
<div> <input type="radio" value="Apple" name="fruit" />Apple <input type="radio" value="Pear" name="fruit" />Pear <input type="radio" value="Banana" name="fruit" />Banana <input type="radio" value="Orange" name="fruit" />Orange </div>
// 定位特定單選鈕
String xpath = "//input[@type='radio'][@value='Apple']";
WebElement apple = driver.findElement(By.xpath(xpath));
// 選取
apple.click();
// 判斷是否已選取
boolean isSelected = apple.isSelected();
// 取得屬性值
String value = apple.getAttribute("value");
操作方式與單選鈕相同,使用 click() 切換狀態,isSelected() 判斷狀態,此處不再贅述。
掌握這六類核心元素的定位與操作,即可應付大多數 Web 自動化測試場景。建議實際動手練習,熟悉各種定位策略的優缺點。