你应该使用'handler'来管理窗口。
一些网络应用程序有很多框架或多个窗口。一旦 WebDriver 对象被实例化,Selenium WebDriver 就会为每个窗口分配一个字母数字 id。这个唯一的字母数字 id 称为窗口句柄。 Selenium 使用这个唯一的 id 在多个窗口之间切换控制。简单来说,每个唯一的窗口都有一个唯一的 ID,以便 Selenium 在将控件从一个窗口切换到另一个窗口时可以区分。
GetWindowHandle 命令
目的:获取当前窗口的窗口句柄。
String handle= driver.getWindowHandle();//Return a string of alphanumeric window handle
GetWindowHandles 命令
目的:获取当前所有窗口的窗口句柄。
Set<String> handle= driver.getWindowHandles();//Return a set of window handle
切换到窗口命令
目的:WebDriver 支持使用“switchTo”方法在命名窗口之间移动。
driver.switchTo().window("windowName");
或者
或者,您可以将“窗口句柄”传递给“switchTo().window()”方法。知道了这一点,就可以像这样遍历每个打开的窗口:
for (String handle : driver.getWindowHandles()) {
driver.switchTo().window(handle);}
或者
使用迭代器在窗口之间切换:
driver.findElement(By.id(“id of the link which opens new window”)).click();
//wait till two windows are not opened
waitForNumberofWindowsToEqual(2);//this method is for wait
Set handles = driver.getWindowHandles();
firstWinHandle = driver.getWindowHandle(); handles.remove(firstWinHandle);
String winHandle=handles.iterator().next();
if (winHandle!=firstWinHandle){
//To retrieve the handle of second window, extracting the handle which does not match to first window handle
secondWinHandle=winHandle; //Storing handle of second window handle
//Switch control to new window
driver.switchTo().window(secondWinHandle);
详情请看:https://www.toolsqa.com/selenium-webdriver/switch-commands/