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 java.io.File;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
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.openqa.selenium.chrome.ChromeDriver;
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”;

@Test
public void selenium99_Screenshot() throws Exception {

// chrome standalone server
System.setProperty(“webdriver.chrome.driver”,
“C:\\Users\\username\\Downloads\\chromedriver_win32\\chromedriver.exe”);
driver = new ChromeDriver();
driver.manage().window().maximize();

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

// selenium command to open the URL
driver.get(“https://selenium99.com/selenium-web-driver-hands-on/”);
try{
WebElement link3 = driver.findElement(By.linkText(“Third Link”));
if(link3.isDisplayed()){
System.out.println(“Third Link is present.”);
}
}catch(Exception e){
System.out.println(“Third Link is not present in the UI.”);
takeScreenshot(path1);
}

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

}

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

@AfterTest
public void tearDown() {

driver.close();
}
}

Output:

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:

TestNG

Mouse hover events in Selenium WebDriver