如何使用Selenium切换到新窗口?

在我的代码中,我已经使用selenium到达了一个页面,有一个链接在同一页面上作为弹出窗口打开,但该链接正在使用,所以它就像一个新页面在新窗口中打开。

我可以单击该链接并打开页面,但是当我正在执行driver.getWindowHandles()时,它返回的大小仅为1而不是2,因为我无法切换到新窗口。

以下是我使用的代码:

String parent = driver.getWindowHandle(); driver.findElement(By.xpath("//a[@id='abc']")).click(); // after clicking on the link try{ Thread.sleep(1000); Set availableWindows = driver.getWindowHandles();//this set size is // returned as 1 and not 2 String newWindow = null; for (String window : availableWindows) { if (!parent.equals(window)) { newWindow = window; } } assertNotNull(newWindow); // switch to new window driver.switchTo().window(newWindow); // do assert the elements in the new window // and then close the new window driver.close(); // switch to parent driver.switchTo().window(parent); // close main window driver.close();} catch(Exception e){ 

由于弹出窗口是主窗口本身的一部分,即,为什么我无法通过执行getWindowHandle()获得正确的大小;

但我的要求是只保存弹出页面。 现在,每次调用母版页驱动程序时,保存代码都会保存母版页详细信息以及弹出内容。

我有什么办法可以解决弹出页面的驱动程序吗?

保存代码是通用的,在此参考中并不重要。 我想要的只是获取弹出页面的驱动程序

点击链接后你需要等到Selenium意识到现在共有2个窗口。

 String parent = driver.getWindowHandle(); driver.findElement(By.xpath("//a[@id='alertHistoryLink']")).click(); // after clicking on the link // call the method numberOfWindowsToBe as follows WebDriverWait wait = new WebDriverWait(driver, 15, 100); wait.until(numberOfWindowsToBe(2)); public static ExpectedCondition numberOfWindowsToBe(final int numberOfWindows) { return new ExpectedCondition() { @Override public Boolean apply(WebDriver driver) { driver.getWindowHandles(); return driver.getWindowHandles().size() == numberOfWindows; } }; } 

我想要的只是获取弹出页面的驱动程序

编辑:主窗口的驱动程序是弹出窗口的驱动程序,因为弹出窗口本身是主窗口的一部分。 唯一的例外是,如果弹出窗口存在于框架中,则需要切换到框架,然后您可以对弹出窗口中的元素执行操作。

编辑:如果我理解正确,你想获得弹出窗口的页面源。 由于弹出窗口是主窗口的一部分。 我会做的是

popup.getAttribute( “innerHTML的”); 弹出窗口的类型为WebElement。

例如,如果主窗口的HTML是这样的

    .....   ... ... ..  ... ..   

然后

WebElement popup = driver.findElement(By.xpath("//div[@id='popup']"));

 String htmlInsidePopup = popup.getAttribute("innerHTML"); System.out.println(htmlInsidePopup); 

将解决问题。