【发布时间】:2012-07-23 14:07:08
【问题描述】:
我使用 Firefox 驱动程序打开了两个 URL。每当我调用驱动程序时,都会打开新的 firefox 窗口。我必须在这两个窗口之间切换。我该怎么做?
【问题讨论】:
我使用 Firefox 驱动程序打开了两个 URL。每当我调用驱动程序时,都会打开新的 firefox 窗口。我必须在这两个窗口之间切换。我该怎么做?
【问题讨论】:
您可以使用以下代码根据窗口标题在窗口之间切换
private void handleMultipleWindows(String windowTitle) {
Set<String> windows = driver.getWindowHandles();
for (String window : windows) {
driver.switchTo().window(window);
if (driver.getTitle().contains(windowTitle)) {
return;
}
}
}
类似地,您可以使用 URL 或其他一些条件来切换窗口。
【讨论】:
我也添加了切换回 mainWindowHandle 的范围。
如果您正在处理具有不同标题的窗口,您可以尝试使用以下功能。
private String mainWindowsHandle; // Stores current window handle
public static boolean swithToWindow(WebDriver driver,String title){
mainWindowsHandle = driver.getWindowHandle();
Set<String> handles = driver.getWindowHandles(); // Gets all the available windows
for(String handle : handles)
{
driver.switchTo().window(handle); // switching back to each window in loop
if(driver.getTitle().equals(title)) // Compare title and if title matches stop loop and return true
return true; // We switched to window, so stop the loop and come out of funcation with positive response
}
driver.switchTo().window(mainWindowsHandle); // Switch back to original window handle
return false; // Return false as failed to find window with given title.
}
【讨论】: