Taking Screenshots

TakesScreenshot

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import java.nio.file.*;

File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);   // temp PNG
Path target = Path.of("target", "screenshots", "home-page.png");
Files.createDirectories(target.getParent());
Files.copy(src.toPath(), target, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Saved " + target + " (" + Files.size(target) / 1024 + " KB)");

Example

Output:

Run ScreenshotTest.main()

Example output

Saved target/screenshots/home-page.png (412 KB)

Other Output Types

OutputTypeGivesUse
FILEa temporary PNG filesave to disk
BYTESbyte[]attach to Allure / Extent reports
BASE64a Base64 stringembed in an HTML report

Note: A screenshot shows the visible viewport only. Firefox has ((FirefoxDriver) driver).getFullPageScreenshotAs(...) for the whole page.