9
我使用Firefox驱动程序打开两个URL。每当我调用驱动程序,新的Firefox窗口打开。我必须在这两个窗口之间切换。我怎样才能做到这一点?使用Selenium WebDriver在两个浏览器窗口之间切换
我使用Firefox驱动程序打开两个URL。每当我调用驱动程序,新的Firefox窗口打开。我必须在这两个窗口之间切换。我怎样才能做到这一点?使用Selenium WebDriver在两个浏览器窗口之间切换
你可以用下面的代码基于窗口的标题
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.
}
谢谢,它为我工作。 :) – 2012-12-18 20:14:44
我也是!这是非常好的方法 – sircapsalot 2013-09-12 19:43:54