Ramanujan R
Ramanujan R

Reputation: 1719

How to Take screenshot using Robot Framework in selenium webdriver

I'm working on an automation project in java using selenium. When there is a failure, need to take a screenshot of web view. Used TakesScreenshot and it's working fine both in chrome-driver and in phantomjs-driver.

But this fails when an alert box is present. After some research, I understood that Selenium can't take a screenshot if alert is present. Alert must be handled first. And I can use java.awt.Robot, in such scenario, where the alert box is needed in my screenshot.

But Robot takes screenshot of my screen and won't get the web view, if using phantomjs-driver or if chrome is running minimized. But I need the screenshot with alert box (which represents the failure condition).

Is there any other solution for this issue?

Upvotes: 0

Views: 3087

Answers (1)

optimistic_creeper
optimistic_creeper

Reputation: 2799

If you really want to capture the screen with alert then there is a way. Put your code portion for taking screenshot inside a try-catch block. If any alert found, it will throw an exception and in the catch block handle it.

Code snippet:

Alert alert = null;

    try {
        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrFile, new File("screenshot.png"));
    } catch (Exception e) {
        alert = driver.switchTo().alert();
        if(e.getMessage().contains("unexpected alert open:")){
            //before taking screenshot, you may wait for some moment to be properly visible
            try {
                 BufferedImage screencapture = new Robot().createScreenCapture((new Rectangle(Toolkit.getDefaultToolkit().getScreenSize())));

                     File file = new File("screenshot.jpg");
                     ImageIO.write(screencapture, "png", file);
            } catch (AWTException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    alert.accept(); //or you can use dismiss();

Note: For taking screenshot using robot your window must be visible.

Upvotes: 0

Related Questions