Take and save a screenshot capture with Selenium

As I recently discussed Selenium, it might be useful to know how to take screen captures during tests. I’ve found that putting the function into a java method makes usage a LOT easier… here are the relevant code bits (obviously this will not run on it’s own). Feel free to expand on it as needed as this is just a stub.

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
* @param driver {@code WebDriver}
* @param filename {@code String}
protected static void takeScreenshot(final WebDriver driver, final String suffix){
final String fn = "takeScreenshot("+ driver.getCurrentUrl() +","+suffix+")";
final String filename = "/tmp/screenshot_" + suffix + ".png";

LOGGER.debug("takeScreenshot("+ driver.getCurrentUrl() +","+filename+")");
final File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File(filename));
LOGGER.debug("[EXEC] {} {}",filename, fn);
catch(final IOException ex){


Leave a Reply