Element Screenshot

Capture One Element

WebElement cartSummary = driver.findElement(By.id("cart-summary"));
File shot = cartSummary.getScreenshotAs(OutputType.FILE);    // Selenium 4: just this element
Files.copy(shot.toPath(), Path.of("target/screenshots/cart-summary.png"), StandardCopyOption.REPLACE_EXISTING);

Element screenshots are small and focused: perfect for a bug report about a wrong total, or for visual checks of a logo or banner.

Naming Screenshots

Example

Screenshots from a whole suite need unique, readable names. This builds names from the test name and a timestamp (fixed here so the output is the same every run):

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    static final DateTimeFormatter STAMP = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");

    static String fileName(String testName, String browser, LocalDateTime when) {
        String safe = testName.replaceAll("[^A-Za-z0-9]+", "_").replaceAll("_$", "");
        return safe + "_" + browser + "_" + when.format(STAMP) + ".png";
    }

    public static void main(String[] args) {
        LocalDateTime when = LocalDateTime.of(2026, 10, 21, 14, 5, 9);
        System.out.println(fileName("Login with wrong password", "chrome", when));
        System.out.println(fileName("Cart: total for 3 items?", "firefox", when.plusSeconds(42)));
    }
}

Output

Login_with_wrong_password_chrome_20261021_140509.png
Cart_total_for_3_items_firefox_20261021_140551.png

Tip: In real tests use LocalDateTime.now(). In the advance level a TestNG listener takes a screenshot automatically whenever a test fails.