How to capture a Screenshot of a Web Page, Section, and a Web Element in Selenium

Reading Time: 4 minutes

Hello Everyone! In this blog, we will talk about one of the important features of Selenium for Automation Testing i.e How to Capture a Screenshot of a Web Page, Section, and Web Element through Selenium. So, let’s start.

Why Screenshot is required in Automation Testing?

  • Whenever a tester finds and reports a bug, that bug would not be taken seriously without supporting screenshots or even videos of the issue. This is equally true no matter the type of testing you are doing and that includes selenium automation testing.
  • For automation testing with selenium, these screenshots help to distinguish whether the failures are due to application failure or due to script failure. These are the various scenario in which selenium screenshots would be required-
  1. When application issues occur
  2. When an assertion failure occurs
  3. Where there is some difficulty in finding a web element on a page
  4. Where there is a Timeout in finding web elements on a web page

Capture Screenshot using selenium

Let’s see how can we capture the Screenshot of a Web Page, Section, and Web Element while automating a web application.

  • First, we have to create a new maven project and add the required dependencies in our pom.xml file like this –
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.knoldus</groupId>
    <artifactId>Screenshot</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>16</maven.compiler.source>
        <maven.compiler.target>16</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-chrome-driver</artifactId>
            <version>4.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>5.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.0.0</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.0.0-alpha-7</version>
        </dependency>

    </dependencies>
</project>

Screenshot of a Web Page

  • Here, I’m taking the ‘Knoldus contact us’ webpage to capture a screenshot of an entire page. This feature of capturing screenshots of a whole web page is also present in selenium 3.
  • We will use getScreenshotAs() method to capture the screenshot.
package TakeScreenshot;

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;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

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

        System.setProperty("webdriver.chrome.driver", "src/test/chromedriver_linux64/chromedriver");

        WebDriver driver = new ChromeDriver();

        driver.manage().window().maximize();

        driver.manage().deleteAllCookies();

        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

        driver.get("https://www.knoldus.com/connect/contact-us");

        TakesScreenshot capture = (TakesScreenshot)driver;

        File src = capture.getScreenshotAs(OutputType.FILE);
        File target = new File("Webpage.png");

        FileUtils.copyFile(src,target);

        driver.close();
    }
}
  • We are using TakesScreenshot class and for that created a reference variable “capture” and here we need to assign the “driver” to this particular “capture” variable.
  • Using this variable or object we will call the method getScreenshotAs(), this is the method that will capture the screenshot.
  • In this method, we have to specify the “Target”. So, target will be the OutputType.FILE
  • So, this is our source file and we need to copy our source file to our Destination file. For the destination, we have created one more variable called “target”.
  • Now we have to copy our src file to destination, for this we have to call a method from FileUtils class copyFile()
This is our Screenshot of a contact-us page which is saved in our project as a Webpage.png

Screenshot of a Section

  • Now, we have to capture a particular section of a web page. For example, go to the https://www.knoldus.com/connect/contact-us webpage and very first section of this webpage is a Banner image section and we have to capture this banner only.
package TakeScreenshot;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class Section {
    public static void main(String[] args) throws IOException {
        System.setProperty("webdriver.chrome.driver", "src/test/chromedriver_linux64/chromedriver");

        WebDriver driver = new ChromeDriver();

        driver.manage().window().maximize();

        driver.manage().deleteAllCookies();

        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.get("https://www.knoldus.com/connect/contact-us");

        WebElement pageSection = driver.findElement(By.xpath("//*[contains(@alt, 'Banner')]"));

        File src = pageSection.getScreenshotAs(OutputType.FILE);
        File target = new File("Banner.png");

        FileUtils.copyFile(src,target);

        driver.close();
    }
}
  • Just identify the xpath for this section or any section you want to capture and locate that xpath by driver.findElement() method and save that element in some variable like “pageSection”.
  • Save that element in a variable so that the complete section is considered as a one element.
This is our Banner.png section captured.

Screenshot of a Web Element

  • Capturing a Screenshot of a single or a specific web element is the feature that is available in selenium 4.
  • For example, we have to capture only the Logo of the website or any input field from the whole form available. So, we can easily capture any single element.
package TakeScreenshot;

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

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class SingleElement {
    public static void main(String[] args) throws IOException {
        System.setProperty("webdriver.chrome.driver", "src/test/chromedriver_linux64/chromedriver");

        WebDriver driver = new ChromeDriver();

        driver.manage().window().maximize();

        driver.manage().deleteAllCookies();

        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.get("https://www.knoldus.com/connect/contact-us");

        WebElement name = driver.findElement(By.xpath("//input[@formcontrolname='name']"));
        WebElement company = driver.findElement(By.xpath("//*[contains(@alt, 'Knoldus logo')]"));
        WebElement option = driver.findElement(By.xpath("//select"));

        elementScreenshot(name,"name");
        elementScreenshot(company,"logo");
        elementScreenshot(option,"option");

        driver.quit();

    }

    public static void elementScreenshot(WebElement element, String Filename) throws IOException {
        File srcFile = element.getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(srcFile, new File("./target/" + Filename+".png"));

    }
}
  • We have create three WebElement for “name”, “logo”, and “option” fields and locate the xpaths for all these three elements.
  • Then, create a generic method so that we don’t need to call again and again for different elements.
  • Just pass the Webelement name and your file name in your generic “elementScreenshot” method. This will take three screenshots together.
  • For the Target file in which you want to copy your source file, you can also give any path to store your screenshot.
These are the three screenshots of specific web elements that are flashed by selenium.

I hope this blog will help you to capture any kind of screenshots using selenium, Thank you!

Reference

https://www.selenium.dev/documentation/webdriver/browser/windows/#takeelementscreenshot


Knoldus-blog-footer-image

Written by 

I am Software Consultant - QA at Knoldus Inc. I have completed my B.Tech from Jodhpur Institute of Engineering and Technology.