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

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

public class TakingScreenshot {
	 public WebDriver driver;

	 @BeforeTest
	public void init(){
		driver = new FirefoxDriver();
		driver.manage().window().maximize();
		driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
		driver.get("http://gmail.com");
	}
	 
	 @Test
	 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"));
	 }
	 
	 @AfterTest
	 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

Shekhar Sharma

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

You may also like...

Leave a Reply

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