在 Java 中使用 Selenium WebDriver 打開一個新選項卡
一、簡介
Selenium WebDriver 是一種流行的自動化 Web 測試工具,具有許多功能。自動化 Web 時的常見操作之一是在瀏覽器窗口中打開一個新選項卡。
打開新選項卡在各種情況下都很有用,包括測試多頁面工作流、驗證在新選項卡中打開的外部鏈接、與彈出窗口交互以及在運行測試時模擬多個用戶同時與應用程序的不同部分交互在平行下。
早期的解決方案是自定義腳本,例如發送組合鍵,例如“Ctrl”+“T”,這通常會根據瀏覽器和操作系統產生不同的結果。
在本教程中,我們將探索打開新選項卡的穩定方法——Selenium 4 中引入的[newWindow()](https://w3c.github.io/webdriver/#new-window)
API 和 JavaScript 代碼執行。
2. 使用newWindow()
API
Selenium 4 引入了一個強大而靈活的 API 方法newWindow()
用於在當前瀏覽器會話中創建一個新窗口。它允許我們打開一個新的瀏覽器選項卡並自動切換到它。此方法採用WindowType
參數WINDOW
或TAB
並創建它。語法非常簡單:
driver.switchTo().newWindow(WindowType.TAB);
3. 使用JavaScript
使用 Selenium WebDriver 打開新選項卡的另一種方法是執行 JavaScript 代碼。它涉及使用JavascriptExecutor
接口的executeScript()
方法,它允許我們直接在瀏覽器中運行 JavaScript 代碼。 window.open()
腳本在我們想要對新選項卡進行更多控制時很有用,例如指定要打開的 URL 。
以下是使用此方法打開新選項卡的方法:
((JavascriptExecutor) driver).executeScript("window.open()");
以及如何使用 URL 打開新標籤頁:
((JavascriptExecutor) driver).executeScript("window.open('https://google.com')");
請務必牢記,在執行window.open()
方法後,驅動程序仍將聚焦於原始選項卡。為了與新選項卡上的元素交互,我們需要使用driver.switchTo().window()
方法將驅動程序的焦點切換到該選項卡。
下面是使用 JavaScript 打開後切換到新選項卡的示例:
String newTab = driver.getWindowHandles()
.stream()
.filter(handle -> !handle.equals(originalTab))
.findFirst()
.get();
driver.switchTo().window(newTab);
4。結論
在本文中,我們探索了兩種使用 Selenium 打開新選項卡的方法:Selenium 4 中引入的newWindow()
方法和使用 JavaScript 執行的window.open()
方法。
newWindow()
方法是 Selenium 4 中引入的新 API,它使創建新選項卡或窗口變得簡單直觀。另一方面,使用 JavaScript 執行window.open()
可以更好地控制新選項卡的打開方式,並且可以與早期版本的 Selenium 一起使用。但是,它可能需要更多代碼並且更難使用,尤其是對於初學者而言。
與往常一樣,代碼示例在 GitHub 上可用。