Web 自動化測試中常遇到 <select> 下拉框。直接點擊 <option> 往往不可靠,Selenium 提供專門的 Select 類封裝了豐富的下拉框操作方法,支持單選、多選、按索引/值/可見文本選擇。
<select id="status" class="form-control valid" name="status">
<option value=""></option>
<option value="0">未審核</option>
<option value="1">初審通過</option>
<option value="2">復審通過</option>
<option value="3">審核不通過</option>
</select>
selenium.webdriver.support.ui.Select 構造函數驗證傳入元素必須是 <select> 標籤。主要方法:
select_by_index(index):按 index 屬性選擇(需 option 擁有 index 屬性)。select_by_value(value):按 value 屬性選擇(最常用)。select_by_visible_text(text):按可見文本選擇。from selenium.webdriver.support.ui import Select
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://your-test-url.com")
# 定位 select 元素
sel = driver.find_element_by_xpath("//select[@id='status']")
select_obj = Select(sel)
# 按 value 選擇
select_obj.select_by_value('0') # 未審核
select_obj.select_by_value('1') # 初審通過
select_obj.select_by_value('2') # 復審通過
select_obj.select_by_value('3') # 審核不通過
org.openqa.selenium.support.ui.Select,方法對應:
selectByIndex(int index)selectByValue(String value)selectByVisibleText(String text)package com.jase.base;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class SelectTest {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://www.your_url.com");
// 定位並操作
Select sel = new Select(driver.findElement(By.xpath("//select[@id='status']")));
sel.selectByValue("0"); // 未審核
sel.selectByValue("1"); // 初審通過
sel.selectByValue("2"); // 復審通過
sel.selectByValue("3"); // 審核不通過
}
}
<select>,而非 <option> 或父容器。WebDriverWait 直到選項出現。isMultiple() 判斷,使用 deselectAll()、deselectByValue() 等方法管理多選狀態。selectByVisibleText 或 selectByIndex。Selenium Select 類是處理下拉框的標準方式,跨語言 API 設計一致。實際項目中建議封裝通用工具方法,統一異常處理與等待邏輯,提升腳本穩定性。