Screenshots in Selenium

Most of the time we think to Capture Screenshot in WebDriver when some kind of error or exception surfaces while practicing testing, to resolve the same WebDriver has provided us one interface TakesScreenshot for capturing the screenshot of web application and This interface provides one method names as getScreenshotAs() to capture screenshot in instance of driver.

This getScreenshotAs() method takes argument of type OutputType.File  or  OutputType.BASE64  or  Output.BYTES.

We have taken the screenshot with the help of getScreenshotsAs() method and  and now it’s time to copy this file somewhere in our file system or in our desktop. So for this purpose we further use copyFile() method of the FileUtils class.

Let’s create a program that will take a screenshot of the page in PNG format.

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class ScreenShot {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		WebDriver driver = new FirefoxDriver();
		driver.get("http://www.google.com/");
		File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
		FileUtils.copyFile(scrFile, new File("D:\\screenshot.png"));

	}
}

Above code will open Google page and it would take a snap shot and that snap shot would be saved as screenshot.png in my D: drive.

Leave a Reply

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