在我的网站上,当我在主页上搜索任何内容时,打开一个留下窗口和一个 popunder 窗口。使用selenium我想知道它是否正确打开了拿这两个窗口链接。
我尝试了这个,但它不起作用
public class Utility
{
public static WebDriver getHandleToWindow(String title){
//parentWindowHandle = WebDriverInitialize.getDriver().getWindowHandle(); // save the current window handle.
WebDriver popup = null;
Set<String> windowIterator = WebDriverInitialize.getDriver().getWindowHandles();
System.err.println("No of windows : " + windowIterator.size());
for (String s : windowIterator) {
String windowHandle = s;
popup = WebDriverInitialize.getDriver().switchTo().window(windowHandle);
System.out.println("Window Title : " + popup.getTitle());
System.out.println("Window Url : " + popup.getCurrentUrl());
if (popup.getTitle().equals(title) ){
System.out.println("Selected Window Title : " + popup.getTitle());
return popup;
}
}
System.out.println("Window Title :" + popup.getTitle());
System.out.println();
return popup;
}
}
答案 0 :(得分:2)
当您只启动一个WebDriver进程时,将只有一个WebDriver。它包含一个窗口句柄列表。您不需要具有WebDriver的多个实例。如果要转到新窗口(或选项卡)然后返回主窗口,则应将主窗口的windowHandle存储在WebDriverInitialize
类中的某个位置。我的示例显示了如何将windowHandle存储在Utility类中。
public class Utility
{
public static void switchToNewWindow(String title){
Set<String> windowIterator = WebDriverInitialize.getDriver().getWindowHandles();
System.err.println("No of windows : " + windowIterator.size());
for (String s : windowIterator) {
String windowHandle = s;
WebDriverInitialize.getDriver().switchTo().window(windowHandle);
System.out.println("Window Title : " + WebDriverInitialize.getDriver().getTitle());
System.out.println("Window Url : " + WebDriverInitialize.getDriver().getCurrentUrl());
// you may use .getTitle().contains(title) if you cannot predict the full title
if (WebDriverInitialize.getDriver().getTitle().equals(title) ){
break;
}
}
}
public static string mainWindowHandle;
}
WebDriverInitialize.getDriver().get("https://www.rentalhomes.com/");
Utility.mainWindowHandle = WebDriverInitialize.getDriver().getWindowHandle();
...
WebDriverInitialize.getDriver().findElement(By.id("home-page-search-btn")).click();
// Switch to the new window
Utility.switchToNewWindow("San Francisco ...");
// Switch back to main window
WebDriverInitialize.getDriver().switchTo().window(Utility.mainWindowHandle);