How to Take Screenshot in Selenium WebDriver

Screenshot in Selenium

A Screenshot in Selenium Webdriver is used for bug analysis. Selenium webdriver can automatically take screenshots during the execution. But if users need to capture a screenshot on their own, they need to use the TakeScreenshot method which notifies the WebDrive to take the screenshot and store it in Selenium.

Screenshot In Selenium

How to Take Screenshot in Selenium

Here is a step-by-step process on how to capture screenshot in selenium WebDriver

Step 1) Convert web driver object to TakeScreenshot

TakesScreenshot scrShot =((TakesScreenshot)webdriver);

Step 2) Call getScreenshotAs method to create image file

File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);

Step 3) Copy file to Desired Location

Example: In this example we will take screen capture of https://demo.guru99.com/V4/ & save it as C:/Test.png

Here is the screenshot code in selenium:

package Guru99TakeScreenshot;

import java.io.File;

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;

public class Guru99TakeScreenshot {

    @Test

    public void testGuru99TakeScreenShot() throws Exception{

		WebDriver driver ;
    	System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
    	driver = new FirefoxDriver();

        //goto url

        driver.get("https://demo.guru99.com/V4/");

        //Call take screenshot function

        this.takeSnapShot(driver, "c://test.png") ;     

    }

    /**

     * This function will take screenshot

     * @param webdriver

     * @param fileWithPath

     * @throws Exception

     */

    public static void takeSnapShot(WebDriver webdriver,String fileWithPath) throws Exception{

        //Convert web driver object to TakeScreenshot

        TakesScreenshot scrShot =((TakesScreenshot)webdriver);

        //Call getScreenshotAs method to create image file

                File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);

            //Move image file to new destination

                File DestFile=new File(fileWithPath);

                //Copy file at destination

                FileUtils.copyFile(SrcFile, DestFile);

    }

}

NOTE: Selenium version 3.9.0 and above does not provide Apache Commons IO JAR. You can simply download them here and call them in your project

What is Ashot API?

Ashot is a third party utility by Yandex supported by Selenium WebDriver to capture the Screenshots. It takes a screenshot of an individual WebElement as well as a full-page screenshot of a page, which is more significant than screen size.

How to download and configure Ashot API?

There are two methods to configure Ashot API

  1. Using Maven
  2. Manually without using any tool

To configure through Maven:

Configure Through Maven

  • Save the file, and Maven will add the jar to your build path
  • And now you are ready!!!

To configure manually without any dependency tool

  1. Go to https://mvnrepository.com/artifact/ru.yandex.qatools.ashot/ashot
  2. Click on the latest version, for now. It is 1.5.4
  3. Click on the jar, download and save it on your machine

Configure Manually Without Any Dependency Tool

  1. Add the jar file in your build path:
  2. In Eclipse, right-click on the project -> go to properties -> Build Path -> Libraries -> Add External jars
  3. Select the jar file
  4. Apply and Close

Capture Full Page Screenshot with AShot API

Step 1) Create an Ashot object and call takeScreenshot() method if you just want the screenshot for the screen size page.

Screenshot screenshot = new Ashot().takeScreenshot(driver);

But if you want a screenshot of the page bigger then the screen size, call the shootingStrategy() method before calling takeScreenshot() method to set up the policy. Then call a method takeScreenshot() passing the webdriver, for example,

Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);

Here 1000 is scrolled out time in milliseconds, so for taking a screenshot, the program will scroll for each 1000 msec.

Step 2): Now, get the image from the screenshot and write it to the file. You can provide the file type as jpg, png, etc.

ImageIO.write(screenshot.getImage(), "jpg", new File(".\\screenshot\\fullimage.jpg"));

Taking a full-page screenshot of a page which is bigger than screen size.

Example: Here is the example of capturing a full-page screenshot of https://demo.guru99.com/test/guru99home/ and save to file “screenshot.jpg.”

Due to using the ShootingStrategy class of Ashot API, we will be able to capture a full image of a page bigger than the screen size.

Here is the screenshot code in selenium program:

package Guru99;

import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;

public class TestScreenshotUsingAshot {

public static void main(String[] args) throws IOException {
	
System.setProperty("webdriver.chrome.driver", "c:\\chromedriver.exe");
WebDriver driver  = new ChromeDriver();	

driver.get("https://demo.guru99.com/test/guru99home/");
driver.manage().window().maximize();
		
Screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);

ImageIO.write(screenshot.getImage(), "jpg", new File("c:\\ElementScreenshot.jpg"));
	
	}

}

Taking a screenshot of a particular element of the page

Example: Here is the example of capturing element screenshot of Guru 99 logo on https://demo.guru99.com/test/guru99home/ page and save to file “ElementScreenshot.jpg”.

Here is the screenshot code in selenium:

package Guru99;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
public class TestElementScreenshotUsingAshot {
public static void main(String[] args) throws IOException {
	
System.setProperty("webdriver.chrome.driver", "c:\\chromedriver.exe");
WebDriver driver  = new ChromeDriver();	

driver.get("https://demo.guru99.com/test/guru99home/");
driver.manage().window().maximize();
		
// Find the element to take a screenshot

WebElement element = driver.findElement(By.xpath ("//*[@id=\"site-name\"]/a[1]/img"));

// Along with driver pass element also in takeScreenshot() method.

Screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver,element);

ImageIO.write(screenshot.getImage(), "jpg", new File("c:\\ElementScreenshot.jpg"));
	}
}

Image Comparison using AShot

package Guru99;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
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 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 TestImageComaprison {

    public static void main(String[] args) throws IOException {

        System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://demo.guru99.com/test/guru99home/");

        // Find the element and take a screenshot

        WebElement logoElement = driver.findElement(By.xpath("//*[@id=\"site-name\"]/a[1]/img"));
        Screenshot logoElementScreenshot = new AShot().takeScreenshot(driver, logoElemnent);

        // read the image to compare

        BufferedImage expectedImage = ImageIO.read(new File("C:\\Guru99logo.png"));

        BufferedImage actualImage = logoElementScreenshot.getImage();

        // Create ImageDiffer object and call method makeDiff()

        ImageDiffer imgDiff = new ImageDiffer();
        ImageDiff diff = imgDiff.makeDiff(actualImage, expectedImage);

        if (diff.hasDiff() == true) {
            System.out.println("Images are same");

        } else {
            System.out.println("Images are different");
        }
        driver.quit();
    }
}

Summary

  • Ashot API is a freeware from Yandex.
  • It is a utility for taking a screenshot in Selenium.
  • It helps you to take a screenshot of an individual WebElement on different platforms like desktop browsers, iOS Simulator Mobile Safari, Android Emulator Browser.
  • It can take a page screenshot of a page bigger than screen size.
  • This feature has been removed in selenium version 3, so Ashot API is a good option.
  • It can decorate the screenshots.
  • It provides a screenshot comparison.

Read More readmore