How to capture the screen shot in selenium

In the previous post, we have learnt about Maven in detail. In this post, we will learn How to capture the screen shot in selenium ?

We will write a TestNG program where we have created 3 methods using annotations like @BeforeTest, @AfterTest and @Test. Which are handling the following functionalities.

  • @BeforeTest: It will intialize the driver and open the gmail application.
  • @Test: We are capturing the screen shot here.
  • @AfterTest: We will close the browser.

Let’s understand this with the below code.

import java.util.concurrent.TimeUnit;

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.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class TakingScreenshot {
	 public WebDriver driver;

	public void init(){
		driver = new FirefoxDriver();
		driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
	 public void CaptureScreenShot() throws IOException{
		File srcFile =  ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);  // Take screen shot
		//Copy the screen shot to the desired location
		FileUtils.copyFile(srcFile, new File("C:\\Gmail.jpg"));
	 public void tearDown(){
		 driver.close();  //close the browser
This is box title
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...