Selenium + Java · Lesson 31 of 44
Module 31: Screenshots
Your task
Implement captureScreenshotFile:
Write it in the editor, then press Check answer (Ctrl + Enter).
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.OutputType;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
// Page Screenshot:
File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
File destFile = new File("screenshots/failure_" + System.currentTimeMillis() + ".png");
Files.copy(srcFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
// Element Screenshot (Selenium 4 feature):
WebElement errorCard = driver.findElement(By.id("error-card"));
File elementSrc = errorCard.getScreenshotAs(OutputType.FILE);When tests fail on continuous integration, visual evidence is critical. In this lesson, you will master casting to TakesScreenshot, saving files with FileUtils, and capturing element-level screenshots in Selenium 4. Let's capture screenshots!
Part of the Selenium + Java course (Selenium with Java). Practice this concept live in the Selenium Online Compiler or explore our free automation practice form.
In Selenium 4 with Firefox, driver.getFullPageScreenshotAs() is natively supported. For Chrome, CDP (Chrome DevTools Protocol) commands are used.
Ready? Solve the task in the editor
Use Check answer to mark it complete. Hints are there if you need them.
___