31. Capturing Page & Element Screenshots on Test Failure

Taking Screenshots in Selenium 4

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

Task

  • Implement captureScreenshotFile:
  • 1. Accept WebDriver driver.
  • 2. Return ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE).
πŸ’‘Common doubts
Did you like the problem?
Lesson 31 of 44
Java
Loading code editor…
Next