How to take screenshot in selenium webdriver using java with example in 3 ways

What is need of screenshot in software testing?

In this article, we will explore the reasons why screenshots are required in testing and how to take screenshot in selenium webdriver using java with example. Software testing is a critical phase in the SDLC, aimed at ensuring the quality, reliability, and functionality of software applications. During testing, it is essential to have comprehensive and reliable evidence of the application’s behavior, both for verification purposes and for efficient debugging and issue resolution. Here screenshots come into the picture.

Importance of Screenshots in Testing

Screenshots play a crucial role in various aspects of the testing process. Let’s delve into some of the key reasons why screenshots are essential:

Verification and Documentation

Screenshots serve as visual evidence of the expected behavior of an application. They act as snapshots of the application’s user interface at a particular point in time, capturing the state of the application during specific test scenarios. By comparing the actual application state with the expected state, testers can verify whether the application behaves as intended.

Moreover, screenshots provide documentation that helps testers communicate their findings and observations effectively. They serve as concrete evidence, making it easier for testers to illustrate and explain issues, bugs, or discrepancies in the application’s behavior to stakeholders, developers, or fellow testers.

Debugging and Issue Reporting

When encountering unexpected behavior or defects, screenshots become valuable assets for debugging and issue reporting. They provide detailed visual information that can assist developers in identifying the root causes of problems. Testers can annotate screenshots, highlighting areas of interest or adding explanatory notes, to provide developers with contextual information.

By including screenshots in bug reports, testers enhance the clarity and completeness of their bug descriptions. Developers can better understand the reported issues and reproduce them more effectively, ultimately leading to faster bug resolution.

Visual Comparison and Regression Testing

During regression testing, where previously resolved bugs or new changes are tested to ensure the system’s stability, screenshots play a significant role. By comparing screenshots taken during previous test runs with the current ones, testers can quickly identify any visual discrepancies or unintended changes in the application’s appearance.

Screenshot in selenium:

Once you have set up the Selenium WebDriver environment, you can start automating web interactions.

There are 3 ways for how to take screenshot in selenium webdriver using java.

  1. Screenshot of visible part of web page
  2. Screenshot of full web page
  3. Screenshot of particular element of web page

1. How to take screenshot of visible part of web page?

To capture a screenshot, there we first need to navigate to a webpage.

After navigating to the desired webpage, we can proceed to capture a screenshot using the Selenium WebDriver. There is an interface called “TakeScreenshot” in selenium. It provides a method called `getScreenshotAs()` that allows us to capture the screenshot.

Once the screenshot is captured, we need to save it to a file for further analysis or reference.

We can accomplish this by using the Java File I/O operations. Here’s an example:

package doWhileLearn.selenium;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.text.SimpleDateFormat;

import io.github.bonigarcia.wdm.WebDriverManager;

public class DoWhileLearn_ScreenShot_Selenium {

@Test
public void test() throws IOException
{
    WebDriverManager.chromedriver().setup();
    WebDriver driver = new ChromeDriver();
    driver.get("https://google.com");


    String searchWord= "Apple";

    WebElement searchBox = driver.findElement(By.name("q"));
    searchBox.sendKeys(searchWord);
    searchBox.submit();


    TakesScreenshot screenshot_instance = (TakesScreenshot) driver;
    File screenshot_visiblePartOnly = screenshot_instance.getScreenshotAs(OutputType.FILE);
    Timestamp tm=new  Timestamp(System.currentTimeMillis());
    String timestamp = new SimpleDateFormat("yyyy_MM_dd__hh_mm_ss").format(new Date());

    FileUtils.copyFile(screenshot_visiblePartOnly,new File( "F:\\selenium2023\\Screenshots\\googleSearch"+timestamp+".png")) ;

}
}

In the above code, we are opening google , searching for any word example “Apple”. Then type casted driver to TakeScreenshot. Then using getScreenshotAs() method with OutputType as File. Now, We need to copyFile in some location for that we are using copyFile(inputFile, OutputFile) of FileUtils.

Now, as we execute code multiple times in regression, at times we need historical images to compare results. For that, we are using timestamp and appending it after each execution. This way our previous images will not be overwritten by new ones.

Now, output screenshot has been saved in desired location and will only capture visible part of a web page.

2. Screenshot of full web page

To capture a screenshot of the full web page in Selenium using Java, you can utilize the “AShot” library.

What is “AShot“?

AShot is a WebDriver Screenshot utility. Previously we just took screenshot of currently visible page. “AShot” is a powerful library in Selenium that provides extended capabilities for capturing screenshots. It works by leveraging the WebDriver instance to capture screenshots of web pages and individual elements. Here’s an example:

First, you need to add the “AShot” dependency to your project. You can do this by adding the following Maven dependency to your pom.xml file:

Once you have added the dependency, you can use the following code to capture a screenshot of the full web page:

This code snippet uses the “AShot” library to capture the full page screenshot. It uses the viewportPasting strategy to scroll the entire web page and capture the complete screenshot.

The viewportPasting is a shooting strategy provided by the “AShot” library in Selenium. It is used to capture a screenshot of the entire web page, including the content that is not immediately visible within the viewport.

When the viewportPasting strategy is used, it works as follows:

  1. “AShot” captures multiple screenshots
  2. Stitches screenshots together to create a single screenshot of the full page.
  3. It works by scrolling the page in small increments and capturing each visible section
  4. Finaly, combining them into a final screenshot.

By using the viewportPasting strategy, you can capture the complete content of a web page, even if it extends beyond the initial viewport size. This is useful when you need to take screenshots of long pages or pages with scrollable content. The screenshot is then saved as a PNG file.

Let’s understand above code:

  1. Inside the doWhilelLearn_captureFullPageScreenshot method, an instance of AShot is created: Screenshot screenshot = newAShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver); This sets up the AShot instance to work with the WebDriver.
  2. The shootingStrategy method is called on the AShot instance to set the shooting strategy. In this case, ShootingStrategies.viewportPasting(1000) is used, which specifies that the page should be scrolled by 1000 pixels at a time to capture the entire content.
  3. The takeScreenshot method is called on the AShot instance, passing in the WebDriver, to capture the screenshot of the full web page.
  4. The captured screenshot is saved to the specified file path using ImageIO.write(screenshot.getImage(), "PNG", new File(filePath))
  5. Finally, the path of the saved screenshot is printed to the console, and any encountered exceptions are printed to the console as well.

3. Screenshot of particular element of web page

Till now, we have seen how to take screenshot in selenium webdriver using java with example for only visible part of web page and full web page. What if we need to take screenshot of an element only. Good news is that selenium provides a way to do so. In order to take a screenshot of a specific element using Selenium with Java, you can follow these steps:

  1. Locate the WebElement that represents the desired element on the web page. You can use various locator strategies provided by Selenium, such as By.id, By.xpath, By.cssSelector, etc., to find the element.
  2. Once you have located the element, you can capture its screenshot using the getScreenshotAs method provided by the TakesScreenshot interface in Selenium. Cast your Webelement instance to TakesScreenshot to access this method.
  3. Save the screenshot to a file using the FileUtils class from the Apache Commons IO library or any other file manipulation library.

Let’s take a look to following code :

Below is full code snippet for handling all three ways to capture screenshot in selenium with java:

package doWhileLearn.selenium;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;

public class DoWhileLearn_ScreenShot_Selenium {
	String timestamp = new SimpleDateFormat("yyyy_MM_dd__hh_mm_ss").format(new Date());
	static TakesScreenshot screenshot_instance;

	@Test
	public void test() throws IOException {
		WebDriverManager.chromedriver().setup();
		WebDriver driver = new ChromeDriver();
		driver.get("https://google.com");

		String searchWord = "Apple";

		WebElement searchBox = driver.findElement(By.name("q"));
		searchBox.sendKeys(searchWord);
		searchBox.submit();

		doWhileLearn_captureVisiblePageScreenshot(driver,
				"F:\\DoWhileLearn_Workspace_SeleniumJava\\doWhileLearn_selenium\\Screenshots\\doWhileLearnVisibleScreenShot"
						+ timestamp + ".png");
		doWhilelLearn_captureFullPageScreenshot(driver,
				"F:\\DoWhileLearn_Workspace_SeleniumJava\\doWhileLearn_selenium\\Screenshots\\doWhileLearnAShot"
						+ timestamp + ".png");
		doWhileLearn_CapturePageElement(driver,
				"F:\\DoWhileLearn_Workspace_SeleniumJava\\doWhileLearn_selenium\\Screenshots\\doWhileLearn_ElementScreenshot"
						+ timestamp + ".png");

	}

	private static void doWhileLearn_captureVisiblePageScreenshot(WebDriver driver, String filePath)
			throws IOException {
		screenshot_instance = (TakesScreenshot) driver;
		File screenshot_visiblePartOnly = screenshot_instance.getScreenshotAs(OutputType.FILE);
		FileUtils.copyFile(screenshot_visiblePartOnly, new File(filePath));
	}

	private static void doWhilelLearn_captureFullPageScreenshot(WebDriver driver, String filePath) {
		// Capture the screenshot of the full web page
		Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000))
				.takeScreenshot(driver);

		// Save the screenshot to the specified file path
		try {
			ImageIO.write(screenshot.getImage(), "PNG", new File(filePath));
			System.out.println("Full page screenshot captured: " + filePath);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void doWhileLearn_CapturePageElement(WebDriver driver, String filePath) throws IOException {
		WebElement element = driver.findElement(By.xpath("//img[@alt='Google']"));
		screenshot_instance = (TakesScreenshot) element;

		File screenshot_visiblePartOnly = screenshot_instance.getScreenshotAs(OutputType.FILE);
		FileUtils.copyFile(screenshot_visiblePartOnly, new File(filePath));

	}
}

Conclusion

Capturing screenshots during web application testing using Selenium WebDriver is a valuable technique for validating the application’s visual aspects and debugging issues. In this article, we explored how to take screenshots using Selenium WebDriver with Java. By following the outlined steps, you can enhance your testing process and ensure the accuracy of your automated tests.

Now, we will be able to answer below screenshot in selenium interview questions:

  1. Why taking screenshot is an important step in testing?
  2. How to take screenshot in selenium?
  3. How to take screenshot of particular element in selenium?
  4. How to take screenshot of full page in selenium?

Happy Learning !!

Leave a Reply