0
0
Selenium Javatesting~15 mins

Element screenshots in Selenium Java - Build an Automation Script

Choose your learning style9 modes available
Capture screenshot of a specific web element
Preconditions (2)
Step 1: Open browser and navigate to 'https://example.com/login'
Step 2: Locate the username input field by its id 'username'
Step 3: Take a screenshot of the username input field element
Step 4: Save the screenshot as 'username_field.png' in the project directory
✅ Expected Result: Screenshot file 'username_field.png' is created and contains only the username input field image
Automation Requirements - Selenium WebDriver with Java
Assertions Needed:
Verify the screenshot file 'username_field.png' exists after test execution
Best Practices:
Use explicit waits to ensure element is visible before taking screenshot
Use By.id locator for element identification
Handle IOException when saving the screenshot
Use Page Object Model pattern for element locating if applicable
Automated Solution
Selenium Java
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.time.Duration;

public class ElementScreenshotTest {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://example.com/login");

            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
            WebElement usernameField = wait.until(
                ExpectedConditions.visibilityOfElementLocated(By.id("username"))
            );

            File screenshot = usernameField.getScreenshotAs(OutputType.FILE);
            File destination = new File("username_field.png");
            Files.copy(screenshot.toPath(), destination.toPath(), StandardCopyOption.REPLACE_EXISTING);

            if (destination.exists()) {
                System.out.println("Screenshot saved successfully: " + destination.getAbsolutePath());
            } else {
                System.out.println("Failed to save screenshot.");
            }
        } catch (IOException e) {
            System.out.println("IOException occurred while saving screenshot: " + e.getMessage());
        } finally {
            driver.quit();
        }
    }
}

This code starts by setting up the ChromeDriver path and opening the browser to the login page.

It uses an explicit wait to ensure the username input field is visible before proceeding.

Then it captures a screenshot of only that element using getScreenshotAs(OutputType.FILE).

The screenshot file is saved as username_field.png in the project directory.

Finally, it checks if the file exists and prints a success message, handling any IO exceptions that might occur.

The driver quits at the end to close the browser.

Common Mistakes - 4 Pitfalls
Using Thread.sleep() instead of explicit waits before taking the screenshot
{'mistake': 'Taking screenshot of the whole page instead of the specific element', 'why_bad': 'The requirement is to capture only the element, not the entire page, which wastes resources and is less precise.', 'correct_approach': "Use the element's getScreenshotAs method to capture only that element."}
Not handling IOException when saving the screenshot file
Using brittle locators like absolute XPath for the element
Bonus Challenge

Now add data-driven testing to capture screenshots of three different input fields: username, password, and email.

Show Hint