Switching focus to a Popup window and taking a scr

2019-06-01 08:35发布

问题:

I'm writing a testscript in selenium 2 that takes a screenshot of a popup. The popup window is a pdf.

After clicking the link, I'm using the code

try {
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));
} catch (IOException e) {
    e.printStackTrace();
}
}

To take a screenshot, however, that only takes a shot of the main page and not the popup window. Is there a way to have selenium 2, change focus to the new popup, take the screenshot, and then close the popup and switch back to the main window?

回答1:

You have to switch the focus of the driver with something like this:

String mainWindow = driver.getWindowHandle();
for (String handle : driver.getWindowHandles()) {
    if (!handle.equals(mainWindow)) {
        driver.switchTo().window(handle)
        //put your screenshot call here
        driver.close();
        driver.switchTo().window(mainWindow);
    }
}

This of course will take a screenshot of all other windows if you got more of them. Then you need to know the exact window handle and just switcht to that.