How To Take Screenshot In Selenium

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 10, 2024

This tutorial explains the importance of Selenium Screenshot & how to use Ashot to take Screenshot in  Selenium application with examples:

Screenshots are basically used in bug analysis. They help in understanding whether the application works as per the user requirements or not.

For every test case, the output received might be different, sometimes the correct output is received, sometimes we get an error, sometimes error message is received due to missing or insufficient input data, etc. Screenshot helps in tracking the proofs of actions/outputs received.

=> Check ALL Selenium Tutorials Here

Selenium Screenshots

In this tutorial, we will learn where Selenium screenshots are needed. We will discuss Ashot and how can we use Ashot in Selenium (installation and configuration of ashot()), learn to capture screenshots in Selenium (for entire web page, for a single element on the page and for a currently open window, also comparing 2 images) and then look at a few examples where screenshots are often captured.

Understanding Selenium Screenshots

GmailLogin

The above image is an example of a screenshot captured while executing code from the Gmail website. The image helps in confirming that the user has successfully logged in to the email account with the correct username and password.

Thus, screenshots are very helpful in capturing the actions/output received after an action is performed and hence helps in confirming an action being performed without any issue.

Selenium can automatically take screenshots; we have to just add code for screenshot in the process of any code execution where screenshots are needed.

Where Are Selenium Screenshots Needed

Following would be the possibilities:

  • When there is trouble in finding an element on a web page.
  • Where there is a Timeout in finding web elements on a page.
  • When an error or issue occurs in the system/application.
  • When an assertion failure is encountered.

What Is Ashot

Ashot() is a third party utility that is supported by the Selenium web driver to capture the screenshots.

Ashot() provides below operations in capturing screenshots:

  • Capturing the full page
  • Capturing the web element
  • Comparing images

Let us see how exactly this works in the next section.

Features of Ashot:

  • It is possible to take a screenshot of the entire page.
  • It is possible to take a screenshot of a web element as well, which is supported on various platforms like Android Emulator Browser, iOS Simulator Mobile Safari, the different desktop browsers).
  • Provides a flexible screenshot comparison.
  • Decorates screenshots.

Ashot can take screenshots in three steps:

  • Captures a screenshot of the full page.
  • Find the size and position of the element.
  • Crops the original screenshot.

How Can We Use Ashot In Selenium

Consider the following steps for downloading and configuring Ashot on your machine:

  1. Go to the link.
  2. Find the latest version of the jar file present for Ashot.
  3. Download and save the jar file at a specific path on your machine.
  4. Now for adding the jar file to your project in Eclipse–Go to your project –> Right-click –> go to properties -> select Build Path -> Libraries -> add External jars
  5. Browse the path where the downloaded jar file is saved.
  6. Select the jar file, click on Apply, and close.

Recommended Reading =>> How To Take Screenshot On Mac

How To Capture Screenshots In Selenium

Selenium provides built-in functionality for capturing screenshots. As per the requirement, TakesScreenshot interface is used to take screenshots, while executing the Selenium scripts. Thus, Selenium Webdriver helps in capturing screenshots while code is being executed.

In the below section, we will learn about the different screenshot types that are captured.

Following are the types:

Capturing a screenshot of:

  • Current open window
  • The entire web page
  • Just a specific web element
  • Comparison of screenshot image with the original image

Let us understand the above points in detail.

#1) Current Open Window

Let us look at the implementation of code for handling screenshots in Selenium for the currently open window:

package SeleniumPrograms;

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.Test;

@Test

public class Screenshot {

     public static void main(String[] args) throws IOException {
     // TODO Auto-generated method stub

     WebDriver drv = new FirefoxDriver();
     drv.manage().window().maximize();		      //always write wait code after this
     drv.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);//for page load
     drv.get("https://opensource-demo.orangehrmlive.com/");	        //Testing webpage
     drv.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //for Implicit wait
		
     //Capturing the screenshot

     File f = ((TakesScreenshot) drv).getScreenshotAs(OutputType.FILE);
     FileUtils.copyFile(f, new File("C:/Users/Chait/Desktop/Screenshots/screenshot01.png"));

      //screenshot copied from buffer is saved at the mentioned path.

     System.out.println("The Screenshot is captured.");
		
        }
}

The below image is the output of the above code implementation. Here, the OrangeHRM site is open and the screenshot of the login page is captured.

Current Open Window

[image source]

Thus, we can capture screenshots where ever required while executing code. The screenshot captured is saved in a file with .png or .jpeg extension. We need to give the path where the image file needs to be saved.

#2) The Entire Web Page

Let us look at the below implementation code for capturing a screenshot of the complete page, with the help of Ashot in Selenium webdriver. For this let us consider the example of a page (Jmeter-user-defined-variables) from – softwaretestinghelp.com.

package SeleniumPrograms;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;

public class Screenshot_EntirePage
{
  public static void main(String[] args) throws InterruptedException, IOException
  {
    WebDriver drv = new FirefoxDriver();
    drv.manage().window().maximize();		       //always write wait code after this
    drv.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS); //for page load
    drv.get("https://www.softwaretestinghelp.com/");	                      //Testing webpage
    drv.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  //for Implicit wait

     WebElement auto = drv.findElement(By.xpath("//ul[@id='mega-menu-primary']/li[6]"));
     auto.click();							 //click Automation tab

    WebElement jmeter = drv.findElement(By.linkText("JMeter"));  //link to JMeter page
     jmeter.click();

     //scroll down to open a link among various links, in the Video Tutorials section of the page

     JavascriptExecutor js = (JavascriptExecutor) drv;         
     js.executeScript("window.scrollBy(0,1700)");			//scrolling downwards
     Thread.sleep(1500);

     WebElement udv = drv.findElement(By.linkText("User-Defined Variables"));
     udv.click();				            		//opening User-Defined Variables link
     Thread.sleep(1500);

     //Capturing the Screenshot with the help of  ashot()

      Screenshot screenshot=new AShot().takeScreenshot(drv); 
      ImageIO.write(screenshot.getImage(),"PNG",new File("C:\\Users\\Chait\\Desktop\\Screenshots\\entirepage.png"));

     //The screenshot to be captured will be in .png image format and would be saved at above mentioned path.

        System.out.println("Screenshot for full page is captured successfully!");
      }
}

Here, the jmeter-user-defined-variables page of our website: www.softwaretestinghelp.com is opened and then we have taken a screenshot of this complete web page (with the help of ashot() in selenium) in .png format and saved at the desired path. The same way we can capture a screenshot of the entire page for any web page.

Thus, on implementing the above code for capturing the screenshot of the entire page, the output received is as shown in the below image for a complete web page screenshot.

Entire_Page

#3) A Web Element

Let us look at the below implementation code, with the use of Ashot in Selenium webdriver for capturing screenshot of a specific web element on the web page.

package SeleniumPrograms;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;

@Test
public class Screenshot_WebEle_Ashot {

   public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub

     WebDriver drv = new FirefoxDriver();
     drv.manage().window().maximize();		       //always write wait code after this
     drv.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS); //for page load
     drv.get("https://opensource-demo.orangehrmlive.com/");	          //Testing webpage
     drv.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);   //for Implicit wait
				
     WebElement uname = drv.findElement(By.id("txtUsername"));      //Username....ID....
     uname.sendKeys("Admin");
      
      WebElement pword = drv.findElement(By.id("txtPassword"));       //Password....ID....
      pword.sendKeys("admin123");

      WebElement login_b = drv.findElement(By.xpath("//input[@id='btnLogin']"));
      login_b.click();						       //Login button....XPATH....
	
      WebElement ele = drv.findElement(By.linkText("Maintenance"));
      ele.click();		   //opening link for element for which we want screenshot
		
      // pass driver as well as the element in takeScreenshot() method.

     Screenshot Screenshot_webele = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(100)).takeScreenshot(drv, ele);

     // For saving the screenshot in .png/.jpeg format at the desired location

     ImageIO.write(Screenshot_webele.getImage(),"png",new File("C:\\Users\\Chait\\Desktop\\Screenshots\\element.jpeg"));

     System.out.println("Screenshot for specified element captured successfully!");
		
         }
}

Thus on implementing the above code for capturing a screenshot of a specific element (here Maintenance tab), the output received is as shown in the below image.

Maintenance_WebElement 1

Here, we choose the tab “Maintenance” as an element for which a screenshot is required. Mention the path where we want the screenshot to be saved. The same way we can capture a screenshot for any other element as well on any such web site.

#4) Comparing Screenshot With Original Image

Let us give a look at the below implementation code with the use of Ashot in Selenium webdriver for capturing a screenshot of a logo element on the web page and comparing it with the original logo.

For this let us consider the example of naukri.com:

package SeleniumPrograms;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;

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

import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.comparison.ImageDiff;
import ru.yandex.qatools.ashot.comparison.ImageDiffer;

public class Screen_Compare {

 public static void main(String[] args) throws IOException {
  // TODO Auto-generated method stub

  WebDriver drv = new FirefoxDriver();
  drv.manage().window().maximize();		      //always write wait code after this
  drv.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);    //for page load
  drv.get("https://www.naukri.com/nlogin/login");              	         //Testing webpage
  drv.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);     //for Implicit wait

  // Finding the logo element and capturing its screenshot

  WebElement logo = drv.findElement(By.xpath("//a[@class='nLogo fl']/img"));
  Screenshot logoSrcshot = new AShot().takeScreenshot(drv, logo);

  // Reading the image for comparision

  BufferedImage expectedImage = ImageIO.read(new File("C:\\Users\\Chait\\Desktop\\naukri_Logo.png"));
  BufferedImage actualImage = logoSrcshot.getImage();

  ImageDiffer img_differnece = new ImageDiffer();

 // Creating ImageDiffer object and calling the method makeDiff()

  ImageDiff differnece = img_differnece.makeDiff(actualImage, expectedImage);

  if (differnece.hasDiff() == true)        //Checking the difference using in-built functions)
  {

   System.out.println("Both logo images matched") //in case when no difference found
  }
  
  else
  {
   System.out.println("The logo images are different"); //in case when difference found
  }
  
   }
}

Thus on implementing the above code for comparison of the screenshot of a logo element (here naukri.com logo), the output received is as shown in the below image.

naukri logo

Here, we choose the logo of “naukri.com”, capture its screenshot, and then it is been compared with the original logo. The difference between images is found using in-built functions. If no difference is found in the 2 logo images, the program prints output as “Both logo images matched” else prints “The logo images are different”.

Examples Where Screenshots Are Often Captured

#1) Logout confirmation

In order to login to a website, we need to enter the correct username and password after which we get logged into the website. Then the user performs the required options and once done with the work, the user gets logged out.

So, if we provide a code for screenshot after getting logged out, again login page will be seen which would confirm the logout action. Please see the below image for more details:

logout confirmation

#2) Confirmation of a newly created record

Adding code for screenshot after creating a new record confirms the record being created successfully. Please see the below screenshot for more details.

Confirmation of a newly created record

In case when the record is not created, the code would not proceed further to capture screenshot and this would confirm that the record is not being created successfully.

#3) Example of missing/incorrect output

This example includes creating a new record for Job Title on the OrangeHRM website. Here, the field Job Title is marked ‘*’ which means it is a compulsory field. So, the record would not be created until the required fields are filled up and then only we would be able to save the record. Please see the below screenshot for more details.

Example of missing/incorrect output

Conclusion

Thus, in this article we have seen, where Selenium screenshots are needed, then how we can handle Screenshots in Selenium, what is Ashot, how it can be downloaded, configured, and actually used in Selenium. We understood the implementation of code for handling screenshot and also seen a few examples where screenshots are often captured.

=> Read Through The Complete Selenium Guide

Was this helpful?

Thanks for your feedback!

Leave a Comment