How To Capture Screenshots In Selenium? Guide With Examples

Posted by Shalini Baskaran | August 5, 2020
Automation • Selenium Java • Selenium Tutorial •

105619 Views | 13 Min Read

Capture Screenshots In Selenium

Capturing screenshots is pivotal to realize whether your web-application is rendering seamlessly or not. If not, where is it failing? Traditionally, testers were accustomed to capturing screenshots manually for each and every test they ran, which was painstakingly exhausting and time-consuming. However, the introduction of Selenium allowed testers to automated browser testing and testers relied on Selenium screenshots to automatically capture their web-application in multiple browsers or environments without the extra hassle.

In this article, we’re going to deep dive into Selenium Screenshots. We will learn how to capture screenshots in Selenium in different ways. But before we do that, let us recap on the importance of capturing screenshots in Selenium.

Why Is It Important To Capture Screenshots In Selenium Testing?

The entire point of implementing Selenium test automation is to execute tests without interferences and get results instantaneously. Wouldn’t be it good to have an image at hand for when you find a bug? You never know when a test might fail and all your effort will be in vain if you have no proof of the bug. As the saying goes- “A picture is worth a thousand words.” That is why capturing a Selenium screenshot would be considered as an important step in testing as it helps to

  1. Understand the end to end flow of a web application.
  2. Analyze a bug.
  3. Track test execution.
  4. Analyze the behavior of the test in different browsers/environments.
  5. Trace and examine the reason behind test failure.

When To Capture Screenshots In Selenium Testing?

Selenium screenshots can help you analyze anything from a bug to a web element. Listed below are the possible scenarios when you might consider capturing a Selenium screenshot.

  1. Capture screenshot for each and every test case.
  2. Capturing screenshots only when there is a failure.
  3. Capturing screenshots in a specific time interval.
  4. Capturing screenshots in different browsers.
  5. Capturing screenshots of specific elements in a webpage.
  6. Capturing screenshots in specific checkpoints.

Now, I will show you how to capture a screenshot in Selenium in different ways.

How To Take A Screenshot Using Selenium Webdriver?

The basic concepts on which the Selenium screenshot capture relies on are typecasting and file handling. The screenshot in Selenium is captured and stored in a specified destination provided in the Selenium testing script.

While automating a web application, we can use an interface TakesScreenshot which signals the WebDriver to take a screenshot during test execution. The TakesScreenshot interface is extended by the WebElement interface (an interface extends another interface) and the browser driver classes such as FirefoxDriver, ChromeDriver, OperaDriver, etc implement the same interface (a class implements an interface).

RemoteWebDriver() class implements interfaces like WebDriver(),TakesScreenshot() etc
and to access these methods we have to downcast the driver object.

The method getScreenshotAs() in the interface TakesScreenshot helps in capturing the screenshots and storing it in a specified path. We have another interface OutputType, which is used to specify the output format of the screenshot such as FILE, BYTES, etc.

In the above destination path “./” indicates the current directory and we can specify the subfolder to hold the screenshots taken and the name in which the screenshots have to be saved. As per the above line, the screenshot taken would be stored in ScreenShot_Folder subfolder inside the current working directory in the name of Test1_Login.png file. If the given subfolder doesn’t exist, then on first-time execution of the script the folder gets automatically created.

1. Simple Program To Capture A Screenshot In Selenium WebDriver

Scenario: Navigate to a webpage, enter valid credentials, and take a screenshot of the page before clicking the Login button. Once logged in, verify if an employee record exists in the employee list and capture a screenshot.

TestNG.xml

Once the test has been executed, refresh the project. A new subfolder would be created as mentioned in the script and you will see the Selenium screenshot saved in the path.

capturescreenshot

Below are the captured screenshots.

The first Selenium screenshot shows the login page of the website.

selenium

The second Selenium screenshot shows the search result of an employee.

Selenium screenshot

2. How To Capture A Screenshot In Selenium Only During Failure?

In our Selenium test automation suite, we may have lots of test cases to be executed. Sometimes capturing screenshots for each and every test case wouldn’t be required.
In such cases, we can capture the screenshots only when a failure occurs in the execution. To achieve this, we could use the ITestListener interface from TestNG. If you’re new TestNG then you can refer to our guide on TestNG Listeners.

Scenario: Navigate to a webpage, enter the credentials and click login button.

We split the above scenario into two cases-
Test case1 : Navigate to a webpage
Test case2 : Enter the username and password and click Login.

In case of failure in any test case, a screenshot would be captured and stored in the destination path.

To achieve this, first we have to create a Listener class. This class implements the ITestListener interface. Then click “Add unimplemented methods”.

unimplemented methods

Once after adding all the methods your code will look like below.

Now we can set up the point where the Selenium screenshot has to be taken. In our case, we have to capture a screenshot in Selenium only when a failure occurs.

We can modify the onTestFailure() method to take a screenshot.

Code snippet for two tests

Test case 1: Navigate to the Facebook login page, get the title of the page and check if the page title matches with the original one “Facebook – log in or sign up

Test case 2: Enter the credentials and click the login button, get the title of the page and check if the page title matches the original title “Facebook”. Only upon successful login, we would be able to get this title.

In order to capture screenshots in failed cases, I have intentionally failed the login test case by providing invalid credentials which by the way wouldn’t be redirected to the actual page thereby causing a failure because of the page title mismatch.

TestNG.xml

Console output:

Console output

Once the tests are executed, refresh the project. A Selenium screenshot of the failed test would be saved.

Selenium-screenshot

Screenshot In Selenium

3. How To Capture A Screenshot In Selenium For A Specific WebElement?

Selenium not only provides the option of capturing screenshots of WebPages but also the WebElements that are interacted with. Import the class javax.imageio.ImageIO provides ImageReader and ImageWriter plugins which are used to crop the image of specified WebElement in the webpage by using height, width, and coordinates parameters.

Scenario: Navigate to the Facebook page, enter the credentials, and click the login button.
Capture the screenshot of the Facebook logo and a login button.

logotest

Facebook Logo

Login

loginpage

Different Ways Of Saving The Captured Screenshots

To enhance readability, we can store the captured screenshot in Selenium by naming each of them dynamically. The two most preferred ways are-

  1. Saving the captured screenshots based on the timestamp.
  2. Saving the captured screenshots based on random Id.

Capture Screenshots And Store Them Based On Timestamp

Usually, when you name the Selenium screenshot in the code, each and every time when the test is executed the screenshot would be replaced. So to overcome this, we may use the timestamp logic to save the screenshot as multiple files that are named based on the timestamp in every test execution.

I have added a separate method to capture the screenshots and name them based on the current time of text execution. Different time formats could be used.

Once the tests are executed, the captured screenshots are saved in the desired path based on the timestamp.

Capture Screenshots And Store Based On Random ID

We can use the random class in Java to generate random numbers and store the captured screenshots with this number.

We have to replace the timestamp logic used in previous code with the below

Screenshots captured and saved by the random number generation logic.

Great! You have successfully captured Selenium Screenshots in different ways and learned how to save these screenshots. But what if I told you that there was an easy way to capture Selenium screenshots?

Easiest Way To Capture Selenium Screenshot

The easiest way to capture screenshots in Selenium is by using LambdaTest cloud Selenium Grid of 2000+ real browsers for desktop and mobile.

At LambdaTest, we want to make the Selenium testing experience as convenient as possible. Which is why we provide a toggle button in our Selenium Desired Capabilities Generator.

Selenium Desired Capabilities Generato

This button when turned on will add a capability called ‘visual’ in the desired capabilities class and set its value as true.

If you pass this capability in your Desired Capabilities class while running your Selenium testing script on LambdaTest Selenium Grid then we will generate step by step screenshots for you Selenium automation script.

You can find these step by step screenshots on the Automation dashboard, by going to Automation Logs –> Metadata.

In the Metadata tab, you will find the button to Download All screenshots.

Download All screenshots

Porting your Selenium testing scripts to LambdaTest is easy. All you need to do is specify your LambdaTest username and access key as the environment variables to route your Selenium tests on a Remote WebDriver. Refer to our documentation on TestNG with Selenium.

We also offer RESTful API for capturing Selenium Screenshots for automated browser testing.

Capture Automated Screenshots Without Selenium Scripts

We also offer a feature called Screenshot testing which allows you to capture full page screenshots of your website across 25 different browsers and operating systems. The tests can be executed either in Desktop or Mobile browsers.

You can create full page screenshots without writing any Selenium script in simply two steps.

Step 1: Once logged in, click Visual UI Testing 🡪 Screenshot.
Step 2: Enter the URL of the website you want to test, select the browsers and hit the capture button.

lambdatest-dashboard

This will automatically generate screenshots of your web-application on your selected browsers and operating systems.

Capture Screenshots Behind Login

Step 1: To capture a screenshot behind login functionality, click the Login button and create a New Login profile.

New Login profile

Step 2: Enter the URL of the webpage and click Next.

webpage and click

Step 3: Enter the locators of the username, password, and login button fields. Click Next.

You can select any of the locators as shown below-

Step 4: Enter a valid username and password and click Next.

Step 5: Save the Login Profile.

Step 6: Once saved, a profile would be created.

For capturing a screenshot for the same webpage with the same credentials you can just toggle the user profile.

capturing a screenshot

Step 7 : Select the browsers and the platform to execute the test and click Capture.
Once the test is executed in different browsers and platforms, the Selenium screenshots would be captured and displayed.

lambdatest-selenium-grid

The screenshots can also be downloaded and verified.

Also Read: 12 Must-Try Features Of Automated Screenshot Testing On LambdaTest.

Leverage Automated Screenshot API For Effortless Cross Browser Testing

Execution of test cases in multiple browsers, environments, and devices needs a lot of work. Finding the compatible browser version and valid version of devices requires strenuous effort. Even though capturing the screenshots might seem to be a piece of cake, organizing the captured screenshots to track for future reference remains to be complicated.

LambdaTest provides an easy approach to capture screenshots through Automated Screenshot API and storing them by the device/platform followed by the browser version. This way it provides better readability and tracking. The platform in which the screenshot has to be captured while test execution has to be provided as a json object in the request body and multiple browser versions can be written in an array which appears to be a straightforward approach in feeding the input.

Let me show you an example in capturing screenshots across multiple environments through LambdaTest Automated screenshot API.

Step 1: Navigate to https://www.lambdatest.com/support/docs/api-doc/#screenshots and select Automated Screenshots API tab. Click the Authorize button.

LambdaTest Automated

Step 2: Enter your username and access key which has been provided once you have signed into LambdaTest. Click Authorize.

Click Authorize

Step 3: Click Start Screenshot Test and click Try it out.

Start Screenshot Test

Step 4: To request this API to capture a screenshot, we have to construct a request body.

The HTTP method to capture the screenshot in this API is POST.

The request body of the screenshot API is of ContextType JSON and there are different tags that relay information about a webpage’s URL, the webpage to be automated, multiple browsers, platforms and devices on which the test has to be executed, resolution and layout of the screenshot and the preference of sending the captured screenshots via mail.

A sample request body is given below.

Step 5: Once after the request body is constructed, click Execute.

Step 6: On successful execution, we could see the HTTP status code as 200 and test_id has been generated as a response.

Step 7: Navigate to the main page of the LambdaTest App and click the Test Logs tab. We can see the logs of all the tests that have been executed on this platform. To trace the screenshot test here, use the test_id that was generated as a successful response.

LambdaTest App

On scrolling down, the screenshots captured in different browsers, platforms and devices as mentioned in the request body can be seen.

All the screenshots can also be downloaded in a ZIP file and then analyzed in detail. The screenshots would be named by the browser and its version, the platform, and the device in which the test was executed. This will ease the tracking of different test cases.

In case of any incorrect information in the request body like an incorrect browser version or invalid name, an error response would be thrown with 400 status code and relevant error message.

For example, if an invalid version of Google Chrome is given in request payload, an error response would be thrown.

Request body

Response

Apart from the basic webpage screenshot, you can also try taking a screenshot for login functionality using the ‘Screenshot Test with Basic Authentication’ option where you need to provide the username and password in the request body along with the other details seen before.

Final Thoughts

To summarize, I have walked you through the different ways to capture a screenshot in Selenium using the TakesScreenshot interface, ITestListener, ImageIO, Visual UI Testing and Automated Screenshot API in LambdaTest and various logics to save the captured screenshots. We have seen the importance of capturing Selenium screenshots in a web application.

Understanding the end to end flow of a work product is important for any tester as he has to know the entire functionality before starting the Selenium test automation process. Capturing a Selenium screenshot in each step of the test execution provides clarity of the workflow and it also eases the tracking of each test case.

I hope you have gained knowledge in capturing a screenshot in selenium. Step up, try it hands-on and let me know your views on the comment section below. Feel free to share this with your colleagues and friends and as it might help in overcoming the challenges in their Selenium test automation script. Explore the automation features until then Happy Testing…!!!

Written by Shalini Baskaran

Shalini works as a Technical Writer at LambdaTest. She loves to explore recent trends in test automation. Other than test automation, Shalini is always up for travel & adventure.

Related Articles

How To Test PDF Files Using Selenium Automation?

108193 Views | 10 Min Min Read

What Is Jenkins

What Is Jenkins? How & Why To Use It?

113913 Views | 29 Min Min Read

Leave a Reply

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