Selenium + Java · Lesson 31 of 44

0/44 done

Module 31: Screenshots

31. Capturing Page & Element Screenshots on Test Failure

15 minlesson

Your task

Implement captureScreenshotFile:

  1. Accept WebDriver driver.
  2. Return ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE).

Write it in the editor, then press Check answer (Ctrl + Enter).

Taking Screenshots in Selenium 4

java
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);

Key Takeaways & Walkthrough Summary

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.

Common Doubts & Lesson Q&A

Can Selenium take full page screenshots of entire scrollable pages?

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.

Java
Skip