How to take screenshot using Selenium WebDriver

Taking screenshot using selenium is simple and it helps us to debug the failure and to find out the root cause. By looking at screenshot, we can get to know the details why test has failed.

TakesScreenShot interface is used to achieve this task and this TakesScreenShot capability is enabled by default in most of the browsers.

In the below example, web page is having the link with name ‘Third Link and it doesn’t have link with name “Fourth Link“. Here script is trying to verify, whether link is present or not in the UI.

Screenshot using selenium:

package com;import;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;

public class Screenshot {

static WebDriver driver;
String path1 = “C:\\Downloads\\Screenshot1.png”;
String path2 = “C:\\Downloads\\Screenshot2.png”;

public void selenium99_Screenshot() throws Exception {

// chrome standalone server
driver = new ChromeDriver();

driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

// selenium command to open the URL
WebElement link3 = driver.findElement(By.linkText(“Third Link”));
System.out.println(“Third Link is present.”);
}catch(Exception e){
System.out.println(“Third Link is not present in the UI.”);

WebElement link4 = driver.findElement(By.linkText(“Fourth Link”));
System.out.println(“Fourth Link is present.”);
}catch(Exception e){
System.out.println(“Fourth Link is not present in the UI.”);


public void takeScreenshot(String path) throws Exception
File screenFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Saves the screenshot in given path.
FileUtils.copyFile(screenFile, new File(path));

public void tearDown() {



Third Link is present.
Fourth Link is not present in the UI.
PASSED: selenium99_Screenshot

Analysis: ‘Third link’ exists in the web page so “Third Link is present” will be printed on the console. ‘Fourth Link’ doesn’t exist on the page so the execution goes to catch block and there it calls the takeScreenshot() method. It takes path as a parameter and saves the screenshot in this location. In this example, you have learned taking screenshot using selenium webdriver.

Other Topics:


Mouse hover events in Selenium WebDriver