Taking Screenshots in Selenium Webdriver

Selenium is the most popular and widely accepted test automation tool for testing web-based applications in the world. Although Selenium is a free and open source tool, it has the technical support of a vast community of Selenium experts. Joint efforts and teamwork continues to improve Selenium technology and it has been improved with many additions.

Selenium webdriver is one such latest addition to the Selenium testing suite which has really revolutionised Selenium testing making it easier, faster and more perfect. Usually, a good number of tests will be executed using Selenium and there are instances when some of the tests may fail. It is important to know the reason for the failure. Here is the need to take screenshots in Selenium Webdriver. Screenshots help to identify the problematic areas and also help in debugging.

Here is a good example for how to take screenshots in Selenium Webdriver.

import java.io.File;
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.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class takeScreenShotExample{
public WebDriver driver;
public void openBrowser() throws Exception {
driver = new FirefoxDriver();
//the below statement will throw an exception as the element is not found, Catch block will get executed and takes the screenshot.

//if we remove the below comment, it will not return exception and screen shot method will not get executed.
catch (Exception e){
System.out.println(“I’m in exception”);
//calls the method to take the screenshot.
public void getscreenshot() throws Exception
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//The below method will save the screen shot in d drive with name “screenshot.png”
FileUtils.copyFile(scrFile, new File(“D:\\screenshot.png”));

In any Selenium tutorial, how to take screenshots in Selenium webdriver will be taught in detail as it is a must whenever executing a test using selenium. Without learning this lesson, you cannot master Selenium.

Leave a Reply

Your email address will not be published. Required fields are marked *