Taking Screenshot Using Webdriver

In selenium webdriver, we can take the screen shot using the below command.
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

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

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s