Steps to capture screenshot with selenium webdriver

Steps to capture screenshot with selenium webdriver

Capturing screenshot of output at time of testing completes our full proof testing of a particular tool which can be beneficial for us in future. After automating huge amount of test cases, it could be a critical point to diagnose why a particular test case has been failed or succeed. For resolving this kind of issue, here we are going to elaborate couple of steps to capture screenshot with selenium webdriver.

Step 1: Create a WebDriver instance.

As per all selenium coding scripts, we need to import libraries to initiate webdriver instance.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

After importing libraries, we need to initiate instance in main methos like this.

WebDriver wdrvr = new ChromeDriver();

Now, we have instance of webdriver and by using that webdriver we'll navigate to webpage in next step.

Step 2: Navigate to a Web Page

In this step we'll navigate to webpage like this.

wdrvr.get("http://etutorialz.com");

Step 3: Capture and save screenshot

Now, we have final step to capture screenshot with automating test cases.

File scrnshot = ((TakesScreenshot)wdrvr).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrnshot, new File("etutorialz.png"));

That's all steps to capture screenshot. For reference, you can also check code implemention given below.

Code Implementation :

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.OutputType;
import org.apache.commons.io.FileUtils;

public class CaptureScreenshot{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\etutorialz\Desktop\Java\chromedriver.exe");
      WebDriver wdrvr = new ChromeDriver();
      String url = "https://etutorialz.com";
      wdrvr.get(url);
      wdrvr.manage().timeouts().implicitlyWait(14, TimeUnit.SECONDS);
      File s = ((TakesScreenshot)wdrvr).getScreenshotAs(OutputType.FILE);
      FileUtils.copyFile(s, new File("etutorialz.png"));
      wdrvr.quit();
   }
}

Now, we are done with code implementaion of capture screenshot with selenium webdriver.