Taking Screenshot in Selenium with Java

Here is the code snippet that allows you take to screenshot during our Selenium execution for the code that is written in Java

And you can use any of the below methods to take a screenshot

 

WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// You can copy it to location of your choice
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));

or you can use below method also

//Method to Capture Screenshot
public String CaptureScreenshot() {
    String path;
    try {
        WebDriver ADriver = new Augmenter().augment(driver);
        //Capturing Screenshot
        File sourcefile = ((TakesScreenshot)ADriver).getScreenshotAs(OutputType.FILE);
        path = "./target/screenshots/" + sourcefile.getName();
        FileUtils.copyFile(sourcefile, new File(path)); 
    }
    catch(IOException e) {
        //Error message if screenshot is not captured
        path = "Failed to capture screenshot: " + e.getMessage();
    }
    return path;
}

 

The below can be placed in one the the classes and the same class can be called and used.

You may also like...