How to Take a Screenshot in Selenium | 4 Different Techniques

Hi all, in this article I will describe how to take viewable area’s, element’s, and an entire page’s screenshot with Selenium WebDriver. Selenium has built-in screenshot functionality but sometimes you need to take screenshots of a specific areas on a page or do some other stuff like ignoring areas.  This is where Yandex’s AShot library comes into your project.

Yandex AShot library is developed by the Yandex team. It has many features like

  • Take a specific area of a page
  • Do scroll and take a screenshot
  • In case you have an infinite scroll page, you can set timeouts
  • Ignore are during the screenshot
  • Change orientation or change resolution

In order to do these operations, we will use Apache commons-io and Yandex’s AShot libraries by combining them with Selenium WebDriver.

Add Dependencies

First, you need to add the following dependencies to your pom.xml.

 <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>

 <!-- https://mvnrepository.com/artifact/ru.yandex.qatools.ashot/ashot -->
        <dependency>
            <groupId>ru.yandex.qatools.ashot</groupId>
            <artifactId>ashot</artifactId>
            <version>1.5.4</version>
        </dependency>

Implement Simple Test Cases

I wrote three methods:

  • screenshotGetScreenShotAs: It takes a viewable screen’s screenshot. Like a print screen operation.
  • screenshotWebElement2: It takes an element screenshot by cropping element size from an entire viewable area’s screenshot.
  • screenshotWebElement3: It takes an element screenshot by using the web element directly from an entire viewable area’s screenshot.
  • screenshotEntirePageAshot: It takes all (entire) screenshots of a website from top to bottom.

Before starting to write the code, please create the screenshots folders under your project folder as shown below.

Not: Folder names in the sample source code is written for Windows OS, in case you use a Unix system, please change them accordingly.

Finally, you can find all method implementations below. While there are many comments in the sample code, if you get lost in it please write a comment and we will try to help you as much as possible.

Sample Code

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
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.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * Created by obaskirt on 10-Dec-17.
 */
public class ScreenShotTest {

    public WebDriver driver;
    private String url = "https://www.amazon.com";
    
    //Current Directory
    private String currentDir = System.getProperty("user.dir");
    
    //GetScreenShot Method Directory and Image File
    private File getSreenShotMethodImageFile = new File (currentDir + 
            "\\ScreenShots\\GetScreenShotMethod\\amazonscreenshot.png");
    
    //Element Screenshot Directory and Image File
    private File webElementImageFile = new File(currentDir + 
            "\\ScreenShots\\Ashot\\WebElement\\logo.png" );
    
    //Entirepage ScreenShot Directory and Image File
    private File entirePageImageFile = new File(currentDir + 
            "\\ScreenShots\\Ashot\\EntirePage\\entirepage.png" );


    //Setup Driver
    @BeforeClass
    public void setupTest() {
        driver = new ChromeDriver();
        //Navigate to URL
        driver.navigate().to(url);
        driver.manage().window().maximize();
    }

    @Test (priority = 0)
    public void screenshotGetScreenShotAs() throws IOException {
        //Take Screenshot of viewable area
        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        //Write Screenshot to a file
        FileUtils.copyFile(scrFile, getSreenShotMethodImageFile);
    }

    @Test (priority = 1)
    public void screenshotWebElement2() throws IOException {
        //Find the element
        WebElement logo = driver.findElement(By.cssSelector(".nav-logo-link .nav-logo-base"));

        // Get viewable area's screenshot
        File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        BufferedImage fullImg = ImageIO.read(screenshot);

        // Get the location of element on the page
        Point point = logo.getLocation();

        // Get width and height of the element
        int eleWidth = logo.getSize().getWidth();
        int eleHeight = logo.getSize().getHeight();

        // Crop element from viewable area's screenshot to get element's screenshot
        BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),
                eleWidth, eleHeight);
        ImageIO.write(eleScreenshot, "png", screenshot);

        //Write Screenshot to a file
        FileUtils.copyFile(screenshot, webElementImageFile);
    }


    @Test (priority = 1)
    public void screenshotWebElement3() throws IOException {
	//Find the element

	WebElement logo = driver.findElement(By.cssSelector("#nav-logo"));
	Screenshot elementScreenShot = new AShot().coordsProvider(new WebDriverCoordsProvider()).takeScreenshot(driver, logo);
	try {
		ImageIO.write(elementScreenShot.getImage(), "PNG", webElementImageFile);
	} catch (IOException e) {
		e.printStackTrace();
	}
}


    @Test (priority = 2)
    public void screenshotEntirePageAshot() throws IOException {
        //Take Screenshot of entire page by AShot
        Screenshot entirePageScreenShot = new AShot().
                shootingStrategy(ShootingStrategies.viewportPasting(100)).takeScreenshot(driver);
        //Write Screenshot to a file
        ImageIO.write(entirePageScreenShot.getImage(),"PNG", entirePageImageFile);
    }

    //Close Driver
    @AfterClass
    public void quitDriver() {
        driver.quit();
    }
}

and results:

Entire Page Screenshot

take entire page screenshot in selenium

WebElement Screenshot

Viewable Area’s Screenshot

This is how you can improve the screenshot functionality of your Selenium WebDriver test.

Thanks.
-Onur

7 thoughts on “How to Take a Screenshot in Selenium | 4 Different Techniques”

  1. After I downloaded the jars and uploaded to the project and run the script you provided, I run to different issues. Try to fix it and run the script to get the screen shot but I wasn’t able to do so.

    My issue is with line 95 and 96. I don’t know what libraries need to be included in order to by pass the issues with those lines.

    Reply
    • Hello Joe, why did you download the jars? Just create a maven project and maven handles all the dependency downloads for you. ;) Would you please try in that way, please? If you face any problem again, I will investigate your problem deeply. ;) Have a good day. :)

      Reply
  2. Hi Onur,

    I have implemented the same way with above example. But i am getting the below error.

    Exception in thread “main” java.awt.image.RasterFormatException: (y + height) is outside of Raster
    at sun.awt.image.ByteInterleavedRaster.createWritableChild(ByteInterleavedRaster.java:1248)
    at java.awt.image.BufferedImage.getSubimage(BufferedImage.java:1202)
    at Main.screenshotWebElement2(Main.java:102)
    at Main.main(Main.java:80)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

    Please advice.

    Thanks
    Thamizh

    Reply
  3. Hi Onur,

    I wanted to ask you how come when i execute my example, it only shows half the logo?, any ideas as to why this is happening.

    Thanks in advance.

    Reply
    • I really don’t know. When I will have time, I will check this again. I will move to a new flat so nowadays I am super busy and I got a new computer. I need to set up the tools. If I will do them, I will check your problem.

      Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.