我有一个带有两个标签的窗口。我正在尝试关闭具有特定标题的选项卡,并将控件切换到另一个选项卡。 这是我的代码:
public static void closeTheWindowWithTitle(String title) {
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
String mainWindow = driver.getWindowHandle();
for(int i = 0; i < tabs.size(); i++) {
log.debug("switched to " + driver.getTitle() + " Window");
if(driver.getTitle().contains(title))
{
driver.switchTo().window(tabs.get(i));
driver.close();
log.debug("Closed the " + driver.getTitle() + " Window");
}
}
driver.switchTo().window(mainWindow);
}
运行代码时,出现以下异常:
org.openqa.selenium.NoSuchWindowException: no such window: target window already closed
from unknown error: web view not found
我无法找出问题所在。请帮忙。
答案 0 :(得分:1)
我猜,您的主窗口的WindowHandle在途中被更改了。您应该可以通过执行与建议的解决方案here类似的操作来解决问题,例如,获取所有WindowHandles并对其进行迭代,最后切换到[0],这应该是剩下的唯一一个了,在关闭第二个之后。
答案 1 :(得分:1)
我希望这将帮助您解决问题,我不想提供代码修复,并且我想逐步向您解释详细过程。
打开firefox / IE / Chrome浏览器,然后导航至https://www.bbc.co.uk
WebDriver driver = new AnyDriveryourusing();
// set implicit time to 30 seconds
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
// navigate to the url
driver.get("https://www.bbc.co.uk");
使用网络驱动程序中存在的getWindowHandle()
方法获取当前(父)窗口的GU ID,并将其值存储在字符串中
// get the Session id of the Parent
String parentGUID = driver.getWindowHandle();
点击“打开新窗口”按钮,应用程序使用Google页面打开新窗口。
// click the button to open new window
driver.findElement(By.id("two-window")).click();
Thread.sleep(5000);
使用getWindowHandles()
中提供的webdriver
方法获取两个窗口(父级和google)的GU ID。将GU ID存储在Set集合中,此Set将具有父浏览器和子浏览器的GU ID
// get the All the session id of the browsers
Set allGUID = driver.getWindowHandles();
重复设置GUID值,如果该值是父值,则在不切换到新窗口时跳过它
// iterate the values in the set
for(String guid : allGUID){
// one enter into if block if the GUID is not equal to parent window's GUID
if(! guid.equals(parentGUID)){
//todo
}
}
使用switchTo().window()
方法切换到窗口,并将子浏览器的GU ID传递给此方法。
// switch to the guid
driver.switchTo().window(guid);
在Google.com中找到搜索栏,然后搜索“成功”
driver.findElement(By.name("q")).sendKeys("success");
关闭Google标签/窗口,然后返回父标签/浏览器窗口
// close the browser
driver.close();
// switch back to the parent window
driver.switchTo().window(parentGUID);
答案 2 :(得分:-1)
您已经关闭,但在检查标题之前没有切换窗口。我已经将代码更新为可以正常工作的地方。
public static void closeTheWindowWithTitle(String title)
{
Set<String> tabs = driver.getWindowHandles();
String mainWindow = driver.getWindowHandle();
for(int i = 0; i < tabs.size(); i++)
{
// you need to switch to the window before checking title
driver.switchTo().window(tabs.get(i));
log.debug("switched to " + driver.getTitle() + " Window");
if(driver.getTitle().contains(title))
{
driver.close();
log.debug("Closed the " + driver.getTitle() + " Window");
break; // this breaks out of the loop, which I'm assuming is what you want when a match is found
}
}
driver.switchTo().window(mainWindow);
}