gpt4 book ai didi

java - Selenium 获取当前打开的弹出窗口和弹出窗口链接

转载 作者:行者123 更新时间:2023-12-02 02:44:17 30 4
gpt4 key购买 nike

在我的网站中,当我在主页上搜索任何内容时,它会打开一个留下窗口和一个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;
}
}

最佳答案

当您仅启动一个 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);

关于java - Selenium 获取当前打开的弹出窗口和弹出窗口链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44897572/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com