How To Take Screenshot In Selenium Java?

Tanay Kumar Deo

Posted On: April 5, 2024

view count309814 Views

Read time11 Min Read

Selenium is an open-source automation tool widely used for testing web applications. It enables developers to create scripts that automate browser activities, evaluate expected results, and ensure application functionality.

When working with automated tests with Selenium, we frequently need to capture a screenshot of the web page or a portion of a web page. This can be useful, especially when debugging test failures or ensuring our application behavior is consistent across browsers.

In this article, we’re going to deep dive into Selenium Screenshots. We will learn about the different ways to capture screenshots in Selenium. If you are preparing for an interview you can learn more through Selenium interview questions.

Why Take Screenshot in Selenium?

In Selenium testing, screenshots serve as crucial elements for various purposes. They provide visual evidence of the web application’s state, aid in debugging, support visual regression testing, and facilitate test results and bug reporting documentation. Mentioned below are a few importance of taking screenshots in Selenium:

  • Debugging Support: Screenshots are instrumental in identifying layout issues, rendering errors, or other anomalies within the application. By visually inspecting screenshots, testers can pinpoint and address potential problems efficiently.
  • Visual Regression Testing: Screenshots are indispensable for conducting visual regression tests. By comparing screenshots taken before and after changes to the application, testers can detect any unintended visual alterations or regressions introduced by the modifications.
  • Documentation of Test Results: Screenshots serve as tangible evidence of test outcomes. They enhance test documentation by visualizing encountered issues, making it easier for developers and stakeholders to comprehend the test results.
  • Bug Reporting: Screenshots simplify the process of reporting bugs. They offer a clear visual representation of encountered issues, enabling developers to quickly understand and address reported bugs.

How To Take Screenshot in Selenium?

To achieve seamless screenshot capture in Selenium, leverage the TakesScreenshot() method. This instructs WebDriver to snapshot and store within the Selenium testing script. The foundation lies in smart typecasting and effective file handling, ensuring precise storage at your designated location.

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.

TakesScreenshot

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.

getScreenshotAs

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.

Simple Program To Capture A Screenshot In Selenium WebDriver

Now we will explore an example to capture a screenshot and store it in our local directory using Selenium and Java. For our example, we will open LambdaTest’s playground website (https://ecommerce-playground.lambdatest.io/) in the Firefox browser.

Code:

This Java code utilizes Selenium WebDriver to automate web browser actions. It opens a website, captures a screenshot, and saves it to a specified directory. It initializes a Firefox WebDriver instance, navigates to a webpage, takes a screenshot, saves it with a filename “ecommerce_plaground.png” and prints the webpage title, and closes the browser.

Captured Screenshot:

"ecommerce_plaground.png

How To Take Multiple Screenshot in Selenium?

Now let’s take an advanced example to capture multiple screenshots and save them in Selenium. In this example, we will open multiple URLs in the Firefox browser and capture screenshots for each of them one by one.

Code:

This Java code utilizes Selenium WebDriver to open multiple tabs, capture screenshots of each tab, and then close all tabs except the current one. It initializes a FirefoxDriver instance, defines URLs to open in new tabs, opens each URL in a new tab, captures screenshots, and closes the extra tabs. The code demonstrates handling multiple tabs using Selenium WebDriver in Java, along with capturing and saving screenshots for each tab. Additionally, it ensures the current tab remains active after the process. Finally, it quits the browser session.

You can refer to the below video tutorial on How To Take Screenshots In Selenium testing.

You can also boost your Selenium automation process with KaneAI by LambdaTest—an AI-driven software testing assistant that empowers teams to create, debug, and refine tests using natural language. Designed specifically for high-speed quality engineering teams, it seamlessly integrates with LambdaTest’s suite of tools for test execution, orchestration, and analysis.

How To Capture Selenium Screenshot using Cloud Based Grid

The easiest way to capture screenshots in Selenium is by using a cloud based Selenium grid like LambdaTest that supports 3000+ real browsers for desktop and mobile.
At LambdaTest, we want to make the Selenium testing experience as convenient as possible. This is why we provide a toggle button in our Selenium Desired Capabilities Generator.

Selenium Desired Capabilities Generator

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

capability called ‘visual’

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.

URL of the website

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.

Screenshots Behind Login

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

 URL of the webpage

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

 password, and login button

You can select any of the locators as shown below:

any of the locators

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

username and password

Step 5: Save the Login Profile

Save the Login

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

profile would be created

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

 screenshot webpage

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.

The screenshots can also be downloaded and verified.

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

Conclusion

Selenium screenshots empower efficient test automation. They provide visual proof of application states, aiding in debugging, regression testing, and documenting results. Selenium’s robust features allow capturing screenshots throughout test execution, ensuring comprehensive coverage.

Selenium offers flexibility. Capture entire pages or specific elements. Whether for assertions, exceptions, or UI checks, Selenium streamlines the process. Advanced features like capturing failed test screenshots, taking multiples, and integrating with cloud solutions further enhance capabilities.

Frequently Asked Questions (FAQs)

Why are screenshots important in Selenium testing?

Screenshots are crucial in Selenium testing as they provide visual evidence of application states, aiding in debugging, regression testing, and documentation. They simplify bug reporting by offering tangible proof of encountered issues.

When should I capture screenshots in Selenium?

Capture screenshots in Selenium when encountering assertion failures, exceptions, page navigation issues, UI verification, or timeouts. Screenshots help in pinpointing the cause of failures and understanding application behavior.

How can I capture screenshots in Selenium using Java?

You can capture screenshots in Selenium using Java by utilizing the TakesScreenshot interface. This involves initializing a WebDriver instance, navigating to a webpage, and using the getScreenshotAs() method to capture screenshots in desired formats.

Can I capture multiple screenshots in Selenium using Java?

Yes, you can capture multiple screenshots in Selenium using Java. Iterate over a list of URLs, open them in separate tabs/windows, and capture screenshots for each page.

How do I capture a screenshot for a specific element in Selenium?

To capture a screenshot for a specific element in Selenium, locate the desired WebElement and use WebDriver methods to capture and crop the screenshot to include only the element’s portion.

Is it possible to capture screenshots for failed test cases in Selenium?

Yes, you can capture screenshots for failed test cases in Selenium. Utilize TestNG listeners or similar mechanisms to capture screenshots when test cases fail, aiding in debugging.

What is the easiest way to capture Selenium screenshots?

The easiest way to capture Selenium screenshots is by using cloud-based Selenium Grid solutions like LambdaTest, offering automated screenshot capture across various browsers and OS.

Author Profile Author Profile Author Profile

Author’s Profile

Tanay Kumar Deo

Tanay kumar deo is a skilled software developer, Upcoming SDET at GlobalLogic (A Hitachi group company). With expertise in Android and web development, he is always eager to expand his skill set and take on new challenges. Whether developing software or sharing his knowledge with others, he is driven by a desire to make a positive impact on the world around him. In addition to his technical abilities, Tanay also possesses excellent blogging and writing skills, which allow him to effectively communicate his ideas and insights to a wider audience.

Blogs: 16



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free