使用Selenium WebDriver在两个浏览器窗口之间切换

9

我使用Firefox Driver打开了两个URL。每次调用driver时,都会打开一个新的Firefox窗口。我需要在这两个窗口之间切换。请问我该如何做?

2个回答

20

你可以使用以下代码根据窗口标题在不同的窗口间进行切换

 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或其他一些条件来切换窗口。


2

我已经添加了回到 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.
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接