How to Capture / Take Screenshot in Selenium WebDriver

Take Screenshot in Selenium WebDriver: When I am working as a manual tester when we are testing an application, and if we find any bug, then we take a screenshot of that and send that to a developer so that they can go through the bug and try to fix. As a part of testing, the screenshot plays a major role because, without that, it’s too difficult to influence the developer.

Similarly, when we automate something in Selenium webdriver, we may also encounter bugs; in that case, we need to capture the screenshots. So, for taking screenshots, selenium provides this feature. With this, we can debug the errors and know which step the test goes to fail.

How To Take Screenshots

Selenium webdriver has the built-in functionality to take screenshots of the web page, which is quite easy because Selenium webdriver has an interface called TakesScreenshot, which can capture the screenshot while executing the Selenium script.

In the TakesScreenshot interface, we have a method called getScreenshotAs(), which can capture and store screenshots in a specified location. Using this method, we can take screenshots of various browsers like Chrome, Firefox, IE, Opera, etc., using their respective web drivers.

The WebDriver interface extends the TakesScreenshot, and all browser drivers like ChromeDriver, FirefoxDriver, InternetExplorerDriver, EdgeDriver, and OperaDriver all implement the TakesScreenshot interface; that’s why in all browsers, we can take the screenshot.

Note: The Selenium webdriver extends the TakesScreenshot interface, and by using the getScreenshotAs() method, this method can only capture the visible area of the web page and not the full page.

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.chrome.ChromeDriver;

public class SeleniumScreenshotTest 
{
   public static void main(String[] args) throws IOException 
   {
      System.setProperty(“webdriver.chrome.driver” , “C:\\drivers\\chromedriver.exe”);
      WebDriver driver = new ChromeDriver();

      driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
      driver.manage().window().maximize();
      driver.get(“https://www.softwaretestingo.com”);

      // down casting WebDriver to use getScreenshotAs method.
      TakesScreenshot ts= (TakesScreenshot)driver;
      // capturing screen shot as output type file
      File screenshotSRC= ts.getScreenshotAs(OutputType.FILE);
      // Defining path and extension of image
      String path=System.getProperty(“user.dir”)+”/ScreenCapturesPNG/”+testStepsName+System.currentTimeMillis()+”.png”;
      // copying file from temp folder to desired location
      File screenshotDest= new File(path);
      FileUtils.copyFile(screenshotSRC, screenshotDest);

      driver.quit();
   }
}

Explanation Of The Above Code

WebDriver driver = new ChromeDriver();

In the above statement, we have upcasted the chromedriver object to webdriver, but to capture the screenshot, we need to downcast the chromedriver object driver to the TakesScreenshot interface.

TakesScreenshot ts= (TakesScreenshot)driver;
File screenshotSRC= ts.getScreenshotAs(OutputType.FILE);

In the above statement, the OutputType is an interface that can provide options to take screenshots in different types such as FILE, BASE64, BYTES, and class. But out of those types, the file type is mostly used.

path=System.getProperty("user.dir")+"/ScreenCapturesPNG/"+testStepsName+System.currentTimeMillis()+".png";

When webdriver takes the screenshot, it is stored in the temp folder. Once the execution is over, the file also gets deleted. That’s why we need to copy the screenshot in a permanent folder. We mentioned the permanent folder, ScreenCapturesPNG, in the above statement, with the file name.

File screenshotDest= new File(path);

In this statement, we are creating a file where we mentioned where it should be stored with a specific name.

How Do You Take Screenshots of The Entire Page

To take a full-page screenshot, we can use the help of third-party tools like AShot to take the whole page screenshot or a specific element screenshot. Now we are going to discuss the AShot tools, and these tools have a rich feature like:

  • Take a specific area of a page
  • Do scroll down and take a screenshot
  • In case you have an infinite scroll page, you can set timeouts
  • Ignore the screenshot
  • Change orientation or change resolution

Let us go through with a simple program and try to understand how it works.

How To Make a Screenshot using AShot

We used two extra jar files for this program, Apache Commons IO and Yandex QATools AShot WebDriver Utility.

For different screenshots, we have created different methods. Here are the methods:

  • screenshotGetScreenShotAs: It takes the viewable screen’s screenshot. Like a print screen operation.
  • screenshotWebElement2: It takes an element screenshot by cropping the element size from an entire viewable area’s screenshot.
  • screenshotWebElement3: It takes an element screenshot by using the web element directly from an entire viewable area’s screenshot.
  • screenshotEntirePageAshot: It takes all (entire) website screenshots from top to bottom.
    Before writing the code, please create the screenshots folders under your project folder, as shown below.

Note: The folder names in the sample source code are for Windows OS; if you use a Unix system, please change them accordingly.

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ScreenShotTest 
{
   public WebDriver driver;
   private String url = "https://www.amazon.com";

   //Current Directory
   private String currentDir = System.getProperty("user.dir");

   //GetScreenShot Method Directory and Image File
   private File getSreenShotMethodImageFile = new File (currentDir +
         "\\ScreenShots\\GetScreenShotMethod\\amazonscreenshot.png");

   //Element Screenshot Directory and Image File
   private File webElementImageFile = new File(currentDir +
         "\\ScreenShots\\Ashot\\WebElement\\logo.png" );

   //Entirepage ScreenShot Directory and Image File
   private File entirePageImageFile = new File(currentDir +
         "\\ScreenShots\\Ashot\\EntirePage\\entirepage.png" );

   //Setup Driver
   @BeforeClass
   public void setupTest() 
   {
      driver = new ChromeDriver();
      //Navigate to URL
      driver.navigate().to(url);
      driver.manage().window().maximize();
   }

   @Test (priority = 0)
   public void screenshotGetScreenShotAs() throws IOException 
   {
      //Take Screenshot of viewable area
      File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
      //Write Screenshot to a file
      FileUtils.copyFile(scrFile, getSreenShotMethodImageFile);
   }

   @Test (priority = 1)
   public void screenshotWebElement2() throws IOException 
   {
      //Find the element
      WebElement logo = driver.findElement(By.cssSelector(".nav-logo-link .nav-logo-base"));

      // Get viewable area's screenshot
      File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
      BufferedImage fullImg = ImageIO.read(screenshot);

      // Get the location of element on the page
      Point point = logo.getLocation();

      // Get width and height of the element
      int eleWidth = logo.getSize().getWidth();
      int eleHeight = logo.getSize().getHeight();

      // Crop element from viewable area's screenshot to get element's screenshot
      BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),
            eleWidth, eleHeight);
      ImageIO.write(eleScreenshot, "png", screenshot);

      //Write Screenshot to a file
      FileUtils.copyFile(screenshot, webElementImageFile);
   }

   @Test (priority = 1)
   public void screenshotWebElement3() throws IOException 
   {
      //Find the element

      WebElement logo = driver.findElement(By.cssSelector("#nav-logo"));
      Screenshot elementScreenShot = new AShot().coordsProvider(new WebDriverCoordsProvider()).takeScreenshot(driver, logo);
      try 
      {
         ImageIO.write(elementScreenShot.getImage(), "PNG", webElementImageFile);
      } 
      catch (IOException e) 
      {
         e.printStackTrace();
      }
   }

   @Test (priority = 2)
   public void screenshotEntirePageAshot() throws IOException 
   {
      //Take Screenshot of entire page by AShot
      Screenshot entirePageScreenShot = new AShot().
            shootingStrategy(ShootingStrategies.viewportPasting(100)).takeScreenshot(driver);
      //Write Screenshot to a file
      ImageIO.write(entirePageScreenShot.getImage(),"PNG", entirePageImageFile);
   }

   //Close Driver
   @AfterClass
   public void quitDriver() 
   {
      driver.quit();
   }
}

Taking Full Page Screenshot Using JavaScript

Above, we have discussed how to take a full-page screenshot with the help of third-party tools. Here, we will learn another alternative way to take the full-page screenshot with the help of JavaScript.

Here is the program:

import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class CaptureFullWebPage 
{

   public static String CaptureScreenShotWithTestStepName(WebDriver driver, String testStepsName)
   {
      try
      {
         // down casting WebDriver to use getScreenshotAs method.
         TakesScreenshot ts= (TakesScreenshot)driver;
         // capturing screen shot as output type file
         File screenshotSRC= ts.getScreenshotAs(OutputType.FILE);
         // Defining path and extension of image
         String path=System.getProperty("user.dir")+"/ScreenCapturesPNG/"+testStepsName+System.currentTimeMillis()+".png";
         // copying file from temp folder to desired location
         File screenshotDest= new File(path);
         FileUtils.copyFile(screenshotSRC, screenshotDest);
         return path;
      }
      catch(Exception e)
      {
         System.out.println("Some exception occured." + e.getMessage());
         return "";
      }
   }

   public static void main(String[] args) throws InterruptedException 
   {
      System.setProperty("webdriver.chrome.driver", "./exefiles/chromedriver.exe");
      WebDriver driver = new ChromeDriver();

      driver.manage().window().maximize();
      driver.get("http://www.softwaretestingo.com/");

      // Down casting driver to JavascriptExecutor
      JavascriptExecutor js = (JavascriptExecutor) driver;

      // It returns height of view part. You can say it as page height. When you click on page down key
      // Page scroll by one page.
      long pageHeight= (long)js.executeScript("return window.innerHeight");
      System.out.println("Page height: "+pageHeight);

      // It is how much you can scroll. It is height if you scroll, you will reach to bottom of page.
      long scrollableHeight= (long)js.executeScript("return document.body.scrollHeight");
      System.out.println("Total scrollable height: "+scrollableHeight);

      // Finding number of pages. Adding 1 extra to consider decimal part.
      int numberOfPages=(int) (scrollableHeight/pageHeight)+1;

      System.out.println("Total pages: "+numberOfPages);

      // Now scrolling page by page
      for(int i=0;i<numberOfPages;i++)
      {
         CaptureFullWebPage.CaptureScreenShotWithTestStepName(driver, "Page "+(i+1));
         js.executeScript("window.scrollBy(0,"+pageHeight+")");
         Thread.sleep(2000);
      }
   }
}

How to Take a Screenshot of a Web Element

Steps to take a screenshot element:

  • Open the browser and navigate to Url:
  • Find the element and Store the element as ‘element.’
  • Take a screenshot of the full page with the output type FILE.
  • Get the element’s location from the stored element using the getLocation() method in Selenium.
  • Get the element size using the getSize() method from Selenium.
  • Create an object for the BufferedImage class using Image.read(imageStored), and this class will be helpful for image processing operations.
  • Use the getSubimage method from BufferedImage, pass coordinates, and width and height for the sub-image. sub-image is nothing but our element. Store the processed image on your machine.
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class GetElementSCreenShot 
{
   public static void main(String[] args) throws Exception 
   {
      // set the geckodriver.exe property
      System.setProperty("webdriver.gecko.driver", "C:/PATH/geckodriver.exe");
      WebDriver driver =new FirefoxDriver();
      driver.manage().window().maximize();
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      driver.get("https://chercher.tech/selenium-webdriver-sample");

      //Locate Image element to capture a screenshot.
      WebElement element = driver.findElement(By.xpath("//input"));

      //Capture entire page screenshot as File.
      //Used TakesScreenshot, OutputType Interface of selenium and File class of java to capture a screenshot of the entire page.
      File screen = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

      //Used selenium Point class to get x y coordinates of Image element.
      //get location(x y coordinates) of the element.
      Point point = element.getLocation();
      int xcordinate = point.getX();
      int ycordinate = point.getY();

      //Used selenium getSize() method to get height and width of element.
      //Retrieve width of element.
      int imageWidth = element.getSize().getWidth();
      //Retrieve height of element.
      int imageHeight = element.getSize().getHeight();

      //Reading full image screenshot.
      BufferedImage img = ImageIO.read(screen);

      //cut Image using height, width and x y coordinates parameters.
      BufferedImage destination = img.getSubimage(xcordinate, ycordinate, imageWidth, imageHeight);
      ImageIO.write(destination, "png", screen);

      //save Image screenshot In D: drive.
      FileUtils.copyFile(screen, new File("D:\\screenshotOfElement.png"));
   }
}

How to Capture Screenshot Different Names Using TestNg?

package com.selenium.basics;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
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 CaptureScreenshotWithDifferentName 
{
   static WebDriver driver;
   public static void main(String[] args) throws InterruptedException, IOException
   {
      CaptureScreenshotWithDifferentName obj=new CaptureScreenshotWithDifferentName();
      driver=new FirefoxDriver();
      driver.get("http://www.softwaretestingblog.in");
      Thread.sleep(3000);
      obj.getScreenShots("manoj");
      driver.close();
   }
   public void getScreenShots(String abc) throws IOException 
   {
      TakesScreenshot ts=(TakesScreenshot)driver;
      File src=ts.getScreenshotAs(OutputType.FILE);
      FileUtils.copyFile(src, new File("G:\\Base_Workspace\\Luna\\Selenium\\Screenshots\\SC" + abc+getTimeStamp() + ".png")); //Files are Stored in G:\Base_Workspace\Luna\Selenium\Screenshots
   }
   public String getTimeStamp() 
   {
      String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
      return timestamp;
   }
}

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

1 thought on “How to Capture / Take Screenshot in Selenium WebDriver”

Leave a Comment