構建一個生產可用的 Selenium 封裝層,實現:多瀏覽器熱插拔、代理配置統一、定位策略標準化、異常處理統一、業務語義化 API(如綁卡選擇)、顯式等待封裝,提升自動化測試代碼的可讀性、穩定性與維護性。
public static WebDriver myDriver(String browser) {
DesiredCapabilities cap = new DesiredCapabilities();
Proxy proxy = new Proxy();
proxy.setHttpProxy("localhost:12104")
.setFtpProxy("localhost:12104")
.setSslProxy("localhost:12104");
cap.setCapability(CapabilityType.PROXY, proxy);
// 避免代理干擾 Selenium 內部通信
cap.setCapability(CapabilityType.ForSeleniumServer.AVOIDING_PROXY, true);
cap.setCapability(CapabilityType.ForSeleniumServer.ONLY_PROXYING_SELENIUM_TRAFFIC, true);
switch (browser.toLowerCase()) {
case "firefox":
ProfilesIni allProfiles = new ProfilesIni();
FirefoxProfile profile = allProfiles.getProfile("default");
driver = new FirefoxDriver(profile);
break;
case "ie":
DesiredCapabilities ieCap = new DesiredCapabilities();
ieCap.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
ieCap.setCapability("ignoreProtectedModeSettings", true);
System.setProperty("webdriver.ie.driver", "tools/IEDriverServer64.exe");
driver = new InternetExplorerDriver(ieCap);
break;
case "chrome":
System.setProperty("webdriver.chrome.driver", "tools/chromedriver.exe");
driver = new ChromeDriver();
break;
default:
throw new IllegalArgumentException("Unsupported browser: " + browser);
}
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // 全局隱式等待
return driver;
}
提供 startTest(remoteUrl, pageUrl) 與 startTest(browser, remoteUrl, pageUrl),支持 Selenium Grid 分布式執行,動態選擇 Firefox/IE 能力。
採用「定位方式 + 操作動作」矩陣設計,覆蓋 id、name、className、linkText、xpath、cssSelector 六大定位器,支持點擊、輸入、獲取文本、清空、連續點擊、狀態判斷(顯示/啟用/選中)八大操作。
public boolean clickById(String id) {
if (!flag) return logSkip("clickById");
try {
// 業務特殊邏輯:處理分頁選項卡點擊
if (id.startsWith("sel_img_") && !id.contains("sel_img_ct")) {
int idx = Integer.parseInt(id.substring(8));
int base = 4;
while (idx > 3) {
driver.findElement(By.id("sel_img_" + base)).click();
idx -= 4;
base += 4;
}
}
driver.findElement(By.id(id)).click();
logAction("clickById", id);
return true;
} catch (Exception e) {
logError(e);
return false;
}
}
clickBindCard(cardNo) 封裝了「查找卡號所在行 → 點擊選中圖標」的完整業務流程,支持分頁翻頁邏輯。clickByXpath(xpath, count) 解決雙擊、多擊場景。excuteJS(js) 繞過 Selenium 無法直接操作的陰影 DOM、只讀屬性、滾動觸發等限制。getFocusAttributeValue(attr) 針對富文本編輯器、彈窗焦點元素屬性提取。public boolean waitForElementByXpath(String xpath) {
try {
new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpath)));
return true;
} catch (TimeoutException e) {
return false;
}
}
建議:棄用隱式等待,全面改用顯式等待(WebDriverWait + ExpectedConditions),精確控制每個元素的等待條件與超時,避免全局超時污染。
| 方法 | 用途 |
|---|---|
| openPage(url) | 頁面導航,自動處理異常 |
| setTimeOut(seconds) | 動態調整隱式等待(不推薦常用) |
| sleep(ms) | 強制休眠(僅調試用,生產禁用) |
| switchToFrame(name) | 切換 iframe 上下文 |
| getTitle() | 獲取頁面標題驗證 |
| endTest() | 優雅關閉 Driver,釋放資源 |
driver 為靜態單例,僅適合單線程測試。並行執行時需改為 ThreadLocal 管理 Driver 實例。項目地址:封裝常用的 selenium 方法