Use the TakesScreenshot interface to capture screenshots. It is built into Selenium WebDriver.
Basic screenshot:
Java
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.OutputType;
import org.apache.commons.io.FileUtils;
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("D:\\testScreenShot.jpg"));
Save with dynamic name:
Java
String timestamp = new SimpleDateFormat("dd-MM-yyyy_HH-mm-ss").format(new Date());
File dest = new File("screenshots/screenshot_" + timestamp + ".png");
FileUtils.copyFile(((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE), dest);
Screenshot of a specific element (Selenium 4+):
Java
WebElement element = driver.findElement(By.id("loginForm"));
File elementScreenshot = element.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(elementScreenshot, new File("screenshots/form.png"));
As bytes (for Extent Reports / Allure):
Java
byte[] screenshotBytes = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
Auto-capture on test failure with TestNG:
Java
@AfterMethod
public void onFailure(ITestResult result) throws IOException {
if (result.getStatus() == ITestResult.FAILURE) {
File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("failures/" + result.getName() + ".png"));
}
}
