首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Selenium 通用封裝庫設計與實踐:多瀏覽器支持、元素操作統一、業務級 API 構建

     編輯:Java 綜合教學

設計目標

構建一個生產可用的 Selenium 封裝層,實現:多瀏覽器熱插拔、代理配置統一、定位策略標準化、異常處理統一、業務語義化 API(如綁卡選擇)、顯式等待封裝,提升自動化測試代碼的可讀性、穩定性與維護性。

一、核心架構:WebDriver 生命週期管理

1.1 瀏覽器工廠模式

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;
}

1.2 遠程驅動支持

提供 startTest(remoteUrl, pageUrl) 與 startTest(browser, remoteUrl, pageUrl),支持 Selenium Grid 分布式執行,動態選擇 Firefox/IE 能力。

二、統一元素操作 API:定位策略解耦

採用「定位方式 + 操作動作」矩陣設計,覆蓋 id、name、className、linkText、xpath、cssSelector 六大定位器,支持點擊、輸入、獲取文本、清空、連續點擊、狀態判斷(顯示/啟用/選中)八大操作。

2.1 統一異常處理模板

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;
    }
}

2.2 關鍵增強點

  • 業務感知:clickBindCard(cardNo) 封裝了「查找卡號所在行 → 點擊選中圖標」的完整業務流程,支持分頁翻頁邏輯。
  • 連續點擊:clickByXpath(xpath, count) 解決雙擊、多擊場景。
  • JS 執行: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),精確控制每個元素的等待條件與超時,避免全局超時污染。

四、測試流程控制 API

方法用途
openPage(url)頁面導航,自動處理異常
setTimeOut(seconds)動態調整隱式等待(不推薦常用)
sleep(ms)強制休眠(僅調試用,生產禁用)
switchToFrame(name)切換 iframe 上下文
getTitle()獲取頁面標題驗證
endTest()優雅關閉 Driver,釋放資源

五、最佳實踐總結

  1. Page Object 模式:將本封裝庫作為底層 Driver,上層構建 Page Object,業務測試代碼零 Selenium API 依賴。
  2. 配置外部化:瀏覽器驅動路徑、代理地址、超時時間通過配置文件注入,避免硬編碼。
  3. 日誌與截圖:在異常捕獲處集成 Allure/ExtentReports 截圖,失敗即可視化。
  4. 並發安全:driver 為靜態單例,僅適合單線程測試。並行執行時需改為 ThreadLocal 管理 Driver 實例。

項目地址:封裝常用的 selenium 方法

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved