Skip to content
🎄 Christmas Advent Calendar 2025 — Unwrap daily testing tips and surprises! View Calendar

Selenium 4: Element screenshotting

08-10-2019 Roy de Kleijn

As from Selenium 4 it is possible to take screenshots of WebElements. The code below shows how you can do that.

@Test
public void elementScreenShot() throws InterruptedException, IOException {
   driver.get("https://www.github.com");

   WebElement svg = driver.findElement(By.id("Layer_1"));

   File file = svg.getScreenshotAs(OutputType.FILE);
   FileUtils.copyFile(file, new File("target/screenshot/element-screenshot.png"));

   // Added this sleep for demo purpose only
   Thread.sleep(15000);
}

Line 7 demonstrates how to take a screenshot of a WebElement.

If you want to perform screenshot comparisons, I recommend you take a look at Ashot API.

Share:
Roy de Kleijn

Test Automation Expert

With over 15 years of experience in software testing and test automation, Roy helps teams improve their testing processes.

Want to learn more?

Check out our trainings and take your test automation skills to the next level.