Capture screenshot of a specific web element
Preconditions (2)
✅ Expected Result: Screenshot file 'username_field.png' is created and contains only the username input field image
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.
Now add data-driven testing to capture screenshots of three different input fields: username, password, and email.
WebElement logo = driver.findElement(By.id("logo"));
File screenshot = logo.getScreenshotAs(OutputType.FILE);
System.out.println(screenshot.exists());WebElement button = driver.findElement(By.name("submit"));
File screenshot = button.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("button.png"));List<WebElement> items = driver.findElements(By.className("product"));
int count = 1;
for (WebElement item : items) {
File src = item.getScreenshotAs(OutputType.FILE);
File dest = new File("product_" + count + ".png");
FileUtils.copyFile(src, dest);
count++;
}Pass the test and this pattern moves unknown