Selenium-10 || Taking Screenshots using Selenium

In this blog, we learn to take screenshots using Selenium. While running the automation script, it is necessary to take screenshots for failed test cases. As a result, we can refer to screenshots for future validation.

Taking Screenshots using Selenium

There are two ways to take screenshots.

  1. Using in-built TakesScreenshot class of Selenium WebDriver.
  2. Via Third-party libraries like AShot library.

Screenshots using TakesScreenshot class

This process contains 5 simple steps to take and save screenshot.

  1. First of all, launch the browser and navigate to the required URL.
  2. Secondly, Converting the current instance of WebDriver into TakeScreenshot object with expected changes on the webpage.
    • TakesScreenshot screenshot= (TakesScreenshot)driver;
  3. Thirdly, Saving screenshot reference as a File in memory, we call it a source file.
    • File srcFile=screenshot.getScreenshotAs(OutputType.FILE);
  4. The next step is to create an object of File to save the above screenshot physically on the hard drive, we call in the destination file.
    • File destFile=new File(“screenshots\\test.jpg”);
  5. In the end, copy the file from memory to the physical location.
    • FileUtils.copyFile(srcFile, destFile);

Note: Download commons-io library files from the below link and add to the Build Path in the project. https://commons.apache.org/proper/commons-io/download_io.cgi

Code Example Using TakeScreenshot Class

import java.io.File;
import java.io.IOException;

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;

/**
 * @author ashok.kumar
 *
 */
public class Sample {

	/**
	 * @param args
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public static void main(String[] args) throws IOException, InterruptedException {

		System.out.println("Defining the type of target browser and location of the browser specific driver...");

		// In the below statment target browser is Chrome and chromeDriver placed under
		System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");

		// Launching the target browser.
		WebDriver driver = new ChromeDriver();
		System.out.println("Chrome Browser launched successfully...");

		// Send the target URL to the current browser's address bar.
		driver.get("http://www.allinoneblogs.com/");
		System.out.println("Target URL launched successfully...");

		// To maximize the browser window.
		driver.manage().window().maximize();

		// Pause the execution for 10 seconds so that page get loaded completely.
		Thread.sleep(10000);

		// Converting Webdriver object into TakeScreenshot object via casting.
		TakesScreenshot screenshot = (TakesScreenshot) driver;

		// Saving screenshot reference as a file in memory.
		File srcFile = screenshot.getScreenshotAs(OutputType.FILE);

		// Create a jpg, png file object to Save the reference object of the file.
		File destFile = new File("screenshots\\test.jpg");

		// Download commons-io library files from link
		// https://commons.apache.org/proper/commons-io/download_io.cgi
		// Copy source file to destination file using FileUtils class.
		FileUtils.copyFile(srcFile, destFile);

		System.out.println("Screenshot Taken...");
	}
}

Using ‘AShot’ third party library

Download the jar file from the below link and add to the Project using a build path, so that we could use the various methods.

https://mvnrepository.com/artifact/ru.yandex.qatools.ashot/ashot/1.5.4

AShot provides a feature that can be used to take a screenshot of :

  1. Current page on the Screen
  2. Full page(if the page size is bigger than the current screen size)
  3. and even we can take a screenshot with the required web element.

Steps to take screenshots using AShot

  1. Capture screenshot for the current WebDriver instance and save in memory.
    • Screenshot ssCurrentScreen = new AShot().takeScreenshot(driver);
  2. Create jpg or png file to save the screenshot on HDD.
    • File destFile = new File(“screenshots\currentScreenSize.jpg”);
  3. Copy or write a screenshot from memory to physical location.
    • ImageIO.write(ssCurrentScreen.getImage(), “jpg”, destFile);

Code Example

The below code example show how to take a screenshot of the current page and full-page using the AShot methods.

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.shooting.ShootingStrategies;
/**
 * @author ashok.kumar
 *
 */
public class Sample2 {

	/**
	 * @param args
	 * @throws InterruptedException
	 * @throws IOException
	 */
	public static void main(String[] args) throws InterruptedException, IOException {
		System.out.println("Defining the type of target browser and location of the browser specific driver...");

		// In the below statment target browser is Chrome and chromeDriver placed under
		System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");

		// Launching the target browser.
		WebDriver driver = new ChromeDriver();
		System.out.println("Chrome Browser launched successfully...");

		// Send the target URL to the current browser's address bar.
		driver.get("https://en.wikipedia.org/wiki/Main_Page");
		System.out.println("Target URL launched successfully...");

		// To maximize the browser window.
		driver.manage().window().maximize();

		// Pause the execution for few seconds so that page get loaded completely.
		Thread.sleep(3000);

		// Capture screenshot for the current screensize and save in memory.
		Screenshot ssCurrentScreen = new AShot().takeScreenshot(driver);

		// Create jpg or png file to save the screnshot on HDD.
		File destFile = new File("screenshots\\currentScreenSize.jpg");

		// Copy or write image from memory to physical location.
		ImageIO.write(ssCurrentScreen.getImage(), "jpg", destFile);

		System.out.println("Screenshot of current Screen size taken...");

		/*
		 * Taking Full page screenshot if page size bigger than screen. Below statement
		 * will scroll the screen after each 500 milisecond.
		 */

		// Capture screenshot while scrolling the screen and save in memory.
		Screenshot ssFullPage = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(500))
				.takeScreenshot(driver);

		// Create jpg or png file to save screenshot
		File destFile1 = new File("screenshots\\Fullpage.jpg");

		// Copy or write image from memory to physical location.
		ImageIO.write(ssFullPage.getImage(), "jpg", destFile1);

		System.out.println("Full page Screenshot taken...");

	}
}

Taking a Screenshot with the web element

First, it Scroll page to the target web element then only it will take a screenshot of the page.

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.shooting.ShootingStrategies;

/**
 * @author ashok.kumar
 *
 */
public class Sample3 {

	/**
	 * @param args
	 * @throws InterruptedException 
	 * @throws IOException 
	 */
	public static void main(String[] args) throws InterruptedException, IOException {
		System.out.println("Defining the type of target browser and location of the browser specific driver...");

		// In the below statment target browser is Chrome and chromeDriver placed under
		System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");

		// Launching the target browser.
		WebDriver driver = new ChromeDriver();
		System.out.println("Chrome Browser launched successfully...");

		// Send the target URL to the current browser's address bar.
		driver.get("https://en.wikipedia.org/wiki/Main_Page");
		System.out.println("Target URL launched successfully...");

		// To maximize the browser window.
		driver.manage().window().maximize();

		// Pause the execution for 10 seconds so that page get loaded completely.
		Thread.sleep(3000);

		
		/*
		 * Taking Screenshot with Particular Element on the webpage.
		 */

		// Idenfiy the element on the webpage for screenshot
		WebElement element=driver.findElement(By.xpath("//*[@id=\"From_today's_featured_list\"]"));
		
		System.out.println(element.getText());
		// Capture screenshot with the target element and save in memory.
		Screenshot ssElement = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver, element);

		// Create jpg or png file to save screenshot
		File destFile2 = new File("screenshots\\ssElement.jpg");

		// Copy or write image from memory to physical location.
		ImageIO.write(ssElement.getImage(), "jpg", destFile2);

		System.out.println("Element Screenshot taken...");
	}
}

Selenium Tutorials:


Leave a Reply

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

Site Statistics

  • Users online: 0 
  • Visitors today : 9
  • Page views today : 15
  • Total visitors : 51,139
  • Total page view: 70,403

   YouTube ChannelQuora

            Ashok Kumar is working in an IT Company as a QA Consultant. He has started his career as a Test Trainee in manual testing in August 2010. Then he moves towards the automation testing after 4 years. He started learning JAVA and Selenium by self to get the knowledge of automation.

       While learning these tools and working on multiple projects, he found that sometimes people get stuck in live scenarios in their project and they have to do lots of RnD to get out of it. So he decided to start blogging only for such scenarios, where anyone facing any problem in their project, can ask any question or give a solution or you can say an alternate solution to achieve the goal successfully.

Later on, he observed that some people want to learn Java but they have few questions in their mind like how to start Java, whether we should go for the online or offline course. So he started writing tutorials on Java, Jira, Selenium, Excel etc.