</>

Technology

Selenium

Difficulty

Intermediate

Interview Question

How to take a screenshot in Selenium WebDriver?

Use TakesScreenshot interface with getScreenshotAs() to capture and save browser screenshots during test execution.

Answer

Use the TakesScreenshot interface to capture screenshots in Selenium.

Full screenshot:

Java
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.OutputType;
import org.apache.commons.io.FileUtils;
import java.io.File;

File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("screenshots/test-failure.png"));

Save with timestamp:

Java
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File dest = new File("screenshots/screenshot_" + timestamp + ".png");
FileUtils.copyFile(((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE), dest);

Screenshot of specific element (Selenium 4):

Java
WebElement element = driver.findElement(By.id("loginForm"));
File elementScreenshot = element.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(elementScreenshot, new File("screenshots/login-form.png"));

Capture on test failure in TestNG:

Java
@AfterMethod
public void captureOnFailure(ITestResult result) throws IOException {
    if (result.getStatus() == ITestResult.FAILURE) {
        File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(src, new File("failures/" + result.getName() + ".png"));
    }
}

Follow AutomateQA

Related Topics