javaselenium-webdriverfirefoxscreenshotwebpage-screenshot

How to take a screenshot in firefox headless (selenium in java)?


I have been able to run a selenium test case with headless Firefox, However when taking a screenshot, the screenshot is not that of the web-page(web-page tested in the testcase) rather, the screenshot is taken of the background (as in. the current window shown (e.g. eclipse IDE running the testcase))

Screenshot function

File screenShotFolder = new File("Screenshots");
        WebDriver driver = getDriver();
        try {
            if (!screenShotFolder.exists() && !screenShotFolder.mkdir()) {
                getLog().error(
                        "Cannot create a new file in the intended location. "
                                + "" + screenShotFolder.getAbsolutePath());
            }
            File scrFile =
                    ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
            String filePath =
                    screenShotFolder.getAbsolutePath() + File.separator
                            + imageName + ".png";
            FileUtils.copyFile(scrFile, new File(filePath));

        } catch (Exception e) {
            e.printStackTrace();
        }

is there any other "options" or "arguments" that need to be set?


Solution

  • Taking a screenshot with headless Firefox should work like for usual driver.

    In the past I used the following approach:

    public static String makeScreenshot() {
        String fileName = System.currentTimeMillis() + "Test";
        File screenshot = Driver.driver.get().getScreenshotAs(OutputType.FILE);
        File outputFile = new File("LoggerScreenshots/" + fileName + ".png");
        System.out.println(outputFile.getAbsolutePath());
        try {
            FileUtils.copyFile(screenshot, outputFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outputFile.getName();
    }
    

    And called it when test execution fails:

    enter image description here