Selenium 4: Element screenshotting

09-10-2019 door 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.

I recommend you to take a look at Ashot API, if you want to perform screenshot comparisson.

Delen: