Taking Screenshots in Selenium [with Code] - The Test Tribe

Taking Screenshots in Selenium [with Code]

Taking Screenshots in Selenium

In the automation testing field, capturing screenshots is very important to verify the behaviour of different aspects of an application. Screenshots are visual evidence that helps testers verify application behaviour, identify issues, and improve test documentation. Selenium WebDriver, a popular tool for automating web applications, offers the best support for capturing screenshots that help in effectively monitoring and validating test results.

Read this article to learn more about the process of taking screenshots in Selenium, its use, and general issues related to it.

Understanding the Importance of Screenshots in Automation Testing

Screenshots in automation testing help testers identify bugs, document test results, and make the debugging process more manageable. It serves as a visual proof of an application’s state at a particular moment, making it easier to analyze issues and verify expected outcomes. Screenshots improve test reports by enhancing communication between development and testing teams. Also, screenshots capture the failure issue when a test fails and add a quick diagnosis and resolution of problems. This helps in contributing to a more efficient and reliable testing process.

When to Take These Screenshots?

  • After Critical Actions:ย Take a screenshot after major user interactions, such as form submissions or navigation events, to verify that the application responds correctly.
  • Upon Test Failures:ย Automatically take screenshots when assertions fail or exceptions occur to document the application’s state during failures.
  • For Visual Validation: Use screenshots to compare the current UI against expected designs to maintain consistency.

Also Read: How to Handle Multiple Windows in Selenium?

How do you take a screenshot in Selenium WebDriver?

Selenium WebDriver allows you to capture the screenshot using the TakesScreenshotย interface. This interface enables the WebDriver instance to capture the current state of the entire page and store it as an image file. Here’s how to implement it in Java:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import java.io.File;
import org.apache.commons.io.FileUtils;

public class ScreenshotUtil {
ย  ย  public static void captureScreenshot(WebDriver driver, String filePath) {
ย  ย  ย  ย  try {
ย  ย  ย  ย  ย  ย  TakesScreenshot screenshot = (TakesScreenshot) driver;
ย  ย  ย  ย  ย  ย  File srcFile = screenshot.getScreenshotAs(OutputType.FILE);
ย  ย  ย  ย  ย  ย  File destFile = new File(filePath);
ย  ย  ย  ย  ย  ย  FileUtils.copyFile(srcFile, destFile);
ย  ย  ย  ย  } catch (Exception e) {
ย  ย  ย  ย  ย  ย  e.printStackTrace();
ย  ย  ย  ย  }
ย  ย  }
}

How to Capture a Screenshot of a Specific Element?

Sometimes, capturing a screenshot of a specific element is more important than the entire page. This helps to focus on particular components or validate specific UI elements.

Method to Screenshot of a Specific Element

Selenium WebDriver allows capturing screenshots of a specific element with the help of getScreenshotAs method, which is available for WebElement objects. This allows testers to select only the portion of a web page for UI purposes, debugging layout issues, etc.

Code Snippet for Capturing Element Screenshots

To capture the screenshot of a specific element, you can first capture the entire page and then crop an image, which is required as per the dimensions. Here’s how you can do it:

import org.openqa.selenium.WebElement;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.awt.Rectangle;
import java.awt.Graphics2D;
public class ElementScreenshotUtil {
ย  ย  public static void captureElementScreenshot(WebDriver driver, WebElement element, String filePath) {
ย  ย  ย  ย  try {
ย  ย  ย  ย  ย  ย  // Capture the entire page screenshot
ย  ย  ย  ย  ย  ย  File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
ย  ย  ย  ย  ย  ย  BufferedImage fullImg = ImageIO.read(screenshot);
ย  ย  ย  ย  ย  ย  // Get the location and size of the element
ย  ย  ย  ย  ย  ย  org.openqa.selenium.Point point = element.getLocation();
ย  ย  ย  ย  ย  ย  int eleWidth = element.getSize().getWidth();
ย  ย  ย  ย  ย  ย  int eleHeight = element.getSize().getHeight();
ย  ย  ย  ย  ย  ย  // Crop the entire page screenshot to get only the element screenshot
ย  ย  ย  ย  ย  ย  BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(), eleWidth, eleHeight);
ย  ย  ย  ย  ย  ย  ImageIO.write(eleScreenshot, "png", screenshot);

ย  ย  ย  ย  ย  ย  File destFile = new File(filePath);
ย  ย  ย  ย  ย  ย  FileUtils.copyFile(screenshot, destFile);
ย  ย  ย  ย  } catch (IOException e) {
ย  ย  ย  ย  ย  ย  e.printStackTrace();
ย  ย  ย  ย  }
ย  ย  }
}

Check Out: Course on Selenium with Python for Test Automation

How to Take a Full-Page Screenshot in Selenium?

Taking a full-page screenshot in Selenium can be challenging, especially when the page content exceeds the visible area of the browser window. Let’s understand it and the steps to perform it.

What are these Full-Page Screenshots in Selenium?

Full-page screenshots capture the entire content of a web page, including elements that are not immediately visible and need scrolling. They are useful for test automation, ensuring that all webpage sections, including headers, footers, and dynamically loaded content, are displayed correctly.

Why Are they needed?

  • Efficient Testing:ย Full-page screenshots cover all the page elements below the fold, rendered and function correctly.
  • Visual Regression Testingย helps detect all types of changes by comparing the current appearance of the entire page against previous versions.
  • UI Consistency Checks:ย This confirms that responsive designs and layouts appear correctly across different devices and browsers.
  • Debugging and Documentation:ย Helps developers and testers analyze layout issues and maintain visual records of the applicationโ€™s interface.

Capture Full-Page Screenshots Step by Step, along with code

Step 1: Set Up Selenium WebDriver

First, you must start the Selenium WebDriver for your preferred browser (Chrome, Firefox, Edge, etc.).

WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();

Step 2: Navigate to the Target Web Page

Load the web page you want to capture.

driver.get("https://www.thetesttribe.com");

Step 3: Use TakesScreenshot to Capture the Full Page

The getFullPageScreenshotAsย featureย is fully supported in Firefox. Here’s the code:

import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
FirefoxOptions options = new FirefoxOptions();
WebDriver driver = new FirefoxDriver(options);
driver.get("https://www.thetesttribe.com");

File screenshot = ((FirefoxDriver) driver).getFullPageScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("fullpage.png"));

Step 4: Use AShot for Full-Page Screenshots (For Chrome and Other Browsers)

Use the following Java code to capture full-page screenshots using AShot.

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;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
public class FullPageScreenshot {
ย  ย  public static void main(String[] args) {
ย  ย  ย  ย  WebDriver driver = new ChromeDriver();
ย  ย  ย  ย  driver.manage().window().maximize();
ย  ย  ย  ย  driver.get("https://www.example.com");
ย  ย  ย  ย  try {
ย  ย  ย  ย  ย  ย  // Capture full-page screenshot using AShot
ย  ย  ย  ย  ย  ย  Screenshot screenshot = new AShot()
ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  .shootingStrategy(ShootingStrategies.viewportPasting(1000))
ย  ย  ย  ย  ย  ย  ย  ย  ย  ย  .takeScreenshot(driver);

ย  ย  ย  ย  ย  ย  ImageIO.write(screenshot.getImage(), "PNG", new File("fullpage_screenshot.png"));
ย  ย  ย  ย  } catch (IOException e) {
ย  ย  ย  ย  ย  ย  e.printStackTrace();
ย  ย  ย  ย  } finally {
ย  ย  ย  ย  ย  ย  driver.quit();
ย  ย  ย  ย  }
ย  ย  }
}

Step 5: Run the code and verify the screenshot

Finally, run the code and check the output directory for the fullpage_screenshot.png file. Verify that the image captures the entire webpage, including the parts outside the viewport.

Common Issues When Taking Screenshots in Selenium

Some of the common issues when taking screenshots in Selenium are discussed below.

What to Do When Screenshots Are Not Captured?

  • Confirm that the Selenium WebDriver is properly initialized.
  • Ensure the required libraries (Apache Commons IO, AShot) are correctly imported.
  • Verify that the WebElement is visible before capturing its screenshot.

Troubleshooting Tips for Selenium Screenshot Failures

  • Handle WebDriver Window Size: Verify that the browser window is maximized before taking screenshots.
  • Use Explicit Waits: Use WebDriverWait to wait for elements to load before capturing screenshots.
  • Check File Permissions: The destination folder has the necessary write permissions.

Also Read About:ย How to Handle iFrames and Frames in Selenium WebDriver?

Best Practices for Taking Screenshots in Selenium

Some of the best practices for taking screenshots in Selenium are:

Organizing Your Screenshot Captures

  • Maintain a structured folder hierarchy to store screenshots by test case and execution date.
  • Use valid file names that indicate the test case and timestamp.

Ensuring Quality in Selenium Screenshots

  • Use high-resolution settings for better clarity.
  • Capture screenshots in PNG format for better quality and lossless compression.
  • Automate screenshot comparisons to detect UI regressions effectively.
ayush singh

Written by

Ayush Singh is an expert tech writer with over five years of experience crafting engaging content in the IT and software testing domains. While working with top brands and industry leaders, Ayush brings a wealth of knowledge and expertise to every piece of writing. With a strong background in software development, quality assurance, and testing methodologies, his technical concepts are clear and to the point. Ayush has contributed to numerous blogs, technical papers, and guides that help professionals stay ahead of the curve in an ever-evolving industry.

Leave a Reply

Your email address will not be published.

Related Posts

Check Thrive EdSchool

Advertisement (Know More)

Get Top Community News

    Top Event and other The Test Tribe updates to your Inbox.

     

    Categories

    Tags

    [sibwp_form id=2]
    The Test Tribe Logo
    Privacy Overview

    This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.