当测试页面同时出现2个或者以上窗口时候,而且新打开的window没有namem,可以使用driver.switchTo().window(handle)来进行切换,直接上代码:
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.NoSuchWindowException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class forEachWindows {
protected void switchWindowByHandle(WebDriver dr, String currentHandle, Set<String> handles) {
Iterator<String> it = handles.iterator();
while (it.hasNext()) {
String newHandles = it.next();
if(currentHandle.equals(newHandles)) {
continue;
}
try {
String newHanlde = it.next();
WebDriver window = dr.switchTo().window(newHanlde);// 切换到新窗口
System.out.println("New page Title is:" + window.getTitle());
System.out.println("New page URL is:" + window.getCurrentUrl());
} catch (Exception e) {
System.out.println("无法切换至新打开的窗口");
System.out.println(e.getMessage());
}
}
}
protected boolean switchToWindowByTitle(WebDriver driver,String windowTitle){
boolean flag = false;
try {
String currentHandle = driver.getWindowHandle();
Set<String> handles = driver.getWindowHandles();
for (String s : handles) {
if (s.equals(currentHandle))
continue;
else {
driver.switchTo().window(s);
if (driver.getTitle().contains(windowTitle)) {
flag = true;
System.out.println("Switch to window: "
+ windowTitle + " successfully!");
break;
} else
continue;
}
}
} catch (NoSuchWindowException e) {
System.out.printf("Window: " + windowTitle + " cound not found!", e.fillInStackTrace());
flag = false;
}
return flag;
}
public void test(){
WebDriver driver = new ChromeDriver();
String currentHandle = driver.getWindowHandle();//获取当前窗口的句柄
Set<String> handles = driver.getWindowHandles();//获取所有窗口的句柄
String windowTitle = driver.getTitle();
switchWindowByHandle(driver, currentHandle, handles);//通过句柄来控制切换到新窗口
//有的业务逻辑需求是要通过窗口的Title来切换窗口
//首先获取当前driver驱动的所有窗口的handle然后进行比对筛选
//如果窗口的title符合预期,则切换,并返回true,反之则返回false。
switchToWindowByTitle(driver, windowTitle);//通过Title来切换窗口
}
}