• Articles
  • Tutorials
  • Interview Questions

How to Take a Screenshot in Selenium With Code?

How to Take a Screenshot in Selenium With Code?

Table of content

Show More

Selenium is an open-source automation tool extensively used for web application testing. It allows developers to write scripts to automate browser actions, validate expected outcomes, and ensure application functionality. It supports multiple programming languages, including Java and Python. Selenium offers cross-browser compatibility and a rich API for comprehensive testing. Its versatility, reliability, and integration with various frameworks make Selenium a popular choice for automating web testing and enhancing software quality.

Check out this Selenium Tutorial for beginners to learn Selenium concepts in depth:

Video Thumbnail

Prerequisites Needed for Understanding the Topic

Prerequisites Needed for Understanding the Topic

Before embarking on your screenshot adventure with Selenium, make sure you have the following essentials in your toolkit: 

  • Selenium WebDriver: Install and set up Selenium WebDriver to interact with web browsers programmatically.
  • Java Development Kit (JDK): Ensure you have the latest JDK installed on your machine to unleash the power of Java in your Selenium scripts.
  • IDE (Integrated Development Environment): Choose your favorite IDE, be it Eclipse, IntelliJ, or Visual Studio Code, to write and execute your Selenium code with ease.
  • Browser Driver: Download the compatible browser driver (e.g., ChromeDriver, GeckoDriver) and configure it to establish a connection between Selenium and your chosen web browser.
  • Dependencies: Include the necessary Selenium and WebDriver dependencies in your project’s build configuration, such as the Selenium Java bindings and WebDriver binaries. 

Now that you have all the ingredients in place, you’re ready to embark on a captivating Selenium screenshot journey that will capture those precious moments of your web application. 

Get 100% Hike!

Master Most in Demand Skills Now!

Why are Screenshots Important in Selenium?

Screenshots are important in Selenium for several reasons. First, they serve as visual evidence of the state of the web application or web page at a specific point in time. They can be used for debugging purposes, helping to identify issues or errors in the application’s layout or rendering.

Second, screenshots can be used for visual regression testing. By capturing screenshots before and after making changes to the application, you can compare them to ensure that the changes did not introduce any unintended visual changes or regressions.

Additionally, screenshots can be helpful for documenting test results and reporting bugs. They provide a visual representation of the issues encountered, making it easier for developers and testers to understand and address them.

Overall, screenshots in Selenium play a vital role in enhancing the effectiveness and efficiency of testing, troubleshooting, and communication during the software development process.

Enroll now in Selenium Training to learn its concepts from experts.

Taking a Screenshot in Selenium

Taking a Screenshot in Selenium

Selenium is a versatile tool that supports various programming languages, allowing users to capture screenshots by utilizing the Selenium WebDriver object. In this guide, we will explain and demonstrate how to take screenshots using Selenium in both Java and Python programming languages.

By following the instructions provided, you’ll be able to easily incorporate screenshot functionality into your Selenium projects.

Step 1: Set Up the Selenium Environment: Before we begin, make sure you have the following components installed:

  1. Java Development Kit (JDK)
  2. Eclipse or any other Java IDE
  3. Selenium WebDriver library
  4. Appropriate browser drivers (e.g., ChromeDriver for Google Chrome)

Step 2: Create a New Java Project: Launch Eclipse and create a new Java project. Set up the project structure and import the Selenium WebDriver library. Configure the build path to include all the required libraries.

Step 3: Set Up Selenium WebDriver: Instantiate a WebDriver object and specify the browser for use. For example, to use Google Chrome, you can use the following code snippet:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ScreenshotExample {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        // Rest of the code goes here
    }
}

Ensure you replace "path/to/chromedriver" with the path to your ChromeDriver executable.

Step 4: Open the Desired URL: Use the get() method to navigate to the desired webpage. For instance, to visit “https://www.example.com“, use the following code:

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

Step 5: Take a Screenshot: To capture a screenshot, use the getScreenshotAs() method of the WebDriver interface. The method returns an instance of the File class representing the captured image. Save the screenshot to a specific location using the following code:

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import java.io.File;
import org.apache.commons.io.FileUtils;
// ...
File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshotFile, new File("path/to/save/screenshot.png"));

Ensure you replace "path/to/save/screenshot.png" with your screenshot’s desired location and filename.

Step 6: Closing the Browser: Once you have captured the screenshot, it is good practice to close the browser to free up system resources. Use the close() method to close the current browser window or the quit() method to exit the entire browser instance.

driver.quit();

Use the TakesScreenshot function to capture a screenshot. By using this method, the Selenium WebDriver is informed to take a screenshot. You may run your tests on several browsers using WebDriver, and you can use a programming language to write your test scripts. Use the getScreenshotAs function to save the Selenium snapshot where you want it. Let’s create a code snippet in Selenium to take a screenshot.

Using Java:
import java.io.IOException;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class SeleniumScreen{
    public static void main(String[] args) throws Exception {
        //Specify the path to your chrome driver
        System.setProperty("webdriver.chrome.driver", "Path_to_your_chrome_driver");
        / Instantiate chrome driver object
        WebDriver driver = new ChromeDriver();
        // Navigate to the testim website
        driver.get("https://www.testim.io/");
        //Use TakesScreenshot method to capture screenshot
        TakesScreenshot screenshot = (TakesScreenshot)driver;
        //Saving the screenshot in desired location
        File source = screenshot.getScreenshotAs(OutputType.FILE);
        //Path to the location to save screenshot
        FileUtils.copyFile(source, new File("./SeleniumScreenshots/Screen.png"));
        System.out.println("Screenshot is captured");
        driver.quit();
    }
}

Using Python:

from selenium import webdriver
driver = webdriver.Chrome("D:\Selenium\chromedriver_win32\chromedriver.exe")
driver.get('https://www.testim.io/')
driver.save_screenshot("screenshot.png")

Screenshot of a Page

When a browser is launched using a webdriver, its default height and width are often close to the size of the screen. However, the height of the webpage may be greater. The code mentioned below first opens the page and obtains its overall dimensions. then modifies the browser’s height to reflect the overall page height. Take a screenshot of the complete page before finishing.

from selenium import webdriver
url = 'https://www.testim.io/'
driver = webdriver.Chrome("D:\chromedriver.exe")
options = webdriver.ChromeOptions()
original_size = driver.get_window_size()
driver.get(url)
#Find height of the page
height = driver.execute_script("return document.body.parentNode.scrollHeight")
driver.quit()
driver = webdriver.Chrome(options=options)
#Change height from default to entire height of the page and take screenshot
driver.set_window_size(original_size['width'], height)
driver.get(url)
driver.save_screenshot('Screenshot.png')
driver.quit()

Screenshot of an Element

You must first locate the element in order to snap a screenshot of it. The code mentioned previously loads the webpage and locates the element with the class"btn-group“. then uses the reference to that specific piece to take a snapshot. You are given a screenshot of just the element you selected in this instance.

from selenium import webdriver 
url = 'https://www.testim.io/' 
driver = webdriver.Chrome("D:\chromedriver.exe") 
driver.get(url) 
#Screenshot of an element 
elem = driver.find_element_by_class_name("btn-group") 
elem.screenshot('Element.png') 
driver.quit()

Also, check out the blog on how to use Selenium with Java.

Screenshot on Error

This method demonstrates a simple way to take a screenshot using a Python script when an error occurs. The script searches for an element on a page after opening it. The test is successful if the element is found. If the element cannot be located, a screenshot is taken.

from selenium import webdriver 
url = 'https://www.testim.io/'
driver = webdriver.Chrome("D:\chromedriver.exe") 
driver.get(url) 
try:
    elem = driver.find_element_by_class_name("dummy-name")
    print("Test passed")
except:
    driver.save_screenshot('Element.png')
driver.quit()

Preparing for a Job Interview? Refer to Selenium Interview Questions to excel in your Interviews!

Benefits of Screenshots in Selenium

Benefits of Screenshots in Selenium

Screenshots play a crucial role in software testing, and when combined with Selenium, they become an invaluable tool for web developers and testers. 

Visual Confirmation: One of the primary benefits of taking screenshots in Selenium is the ability to visually confirm that the web application under test appears as expected. By capturing screenshots at various stages of the testing process, testers can compare them against expected results, ensuring that the user interface and design elements are correctly displayed.

// Capture a screenshot in Selenium
WebDriver driver = new ChromeDriver();
driver.get("https://www.example.com");
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("screenshot.png"));

Debugging and Issue Reporting: Screenshots are invaluable when it comes to debugging and issue reporting. When a test fails, a screenshot can provide crucial information about the state of the application at the time of the failure. Testers can use screenshots to precisely identify UI inconsistencies, error messages, or unexpected behaviors, making it easier to reproduce and fix the issues.

// Capture a screenshot on test failure
try {
    // Perform test steps
    // ...
} catch (AssertionError e) {
    // Capture screenshot on failure
    File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(screenshot, new File("failure_screenshot.png"));
    throw e;
}

Documentation and Reporting: Screenshots serve as visual documentation of test cases, making it easier to communicate test results to stakeholders. Including screenshots in test reports enhances clarity and provides evidence of the test coverage and outcomes. It enables clear and concise reporting, improving communication among team members.

// Capture a screenshot during test execution
// ...
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("test_execution_screenshot.png"));
// …

Cross-Browser and Cross-Platform Testing: Selenium allows testing across multiple browsers and platforms, and taking screenshots helps verify that the web application renders consistently across different environments. Screenshots enable testers to compare the visual appearance of the application across various browsers, ensuring a consistent user experience for all users.

// Capture screenshots across multiple browsers
// ...
List<WebDriver> drivers = new ArrayList<>();
drivers.add(new ChromeDriver());
drivers.add(new FirefoxDriver());
// ...
for (WebDriver driver : drivers) {
    driver.get("https://www.example.com");
    File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(screenshot, new File("browser_screenshot_" + driver.getClass().getSimpleName() + ".png"));
    driver.quit();
}
// …

Regression Testing: When performing regression testing, screenshots captured during a baseline test can be compared against subsequent test runs. By visually comparing screenshots, testers can quickly identify any visual discrepancies, such as layout changes or missing elements, helping to detect unintended side effects of code changes.

// Capture screenshots during baseline test
// ...
File baselineScreenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(baselineScreenshot, new File("baseline_screenshot.png"));
// ...
// Capture screenshots during subsequent test runs
// ...
File currentScreenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(currentScreenshot, new File("current_screenshot.png"));
// ...
// Compare baseline and current screenshots
// …

Training and Knowledge Sharing: Screenshots provide an effective way to train new testers or share knowledge within a team. They can be used to create step-by-step documentation, walkthroughs, or tutorials, enabling newcomers to understand complex test scenarios and learn from past experiences.

UI/UX Improvement: Screenshots facilitate collaboration between developers and designers by capturing the current state of the UI. They help in identifying areas for improvement and providing valuable feedback on the application’s visual appearance and user experience.

Check out the selenium tutorial to learn more about its concepts.

Conclusion

Knowing how to take screenshots in Selenium with code is an essential skill for web developers and testers. By leveraging the power of screenshots, you can visually confirm the appearance of the web application, debug issues effectively, document test cases, and perform cross-browser and regression testing. Screenshots also aid in training, knowledge sharing, and UI/UX improvement. By incorporating screenshots into your testing process, you can enhance the efficiency and quality of your testing efforts, leading to improved software reliability and user satisfaction.

To further enhance your Selenium skills, it is recommended to master the concept of test automation frameworks. Understanding frameworks like TestNG or JUnit can help you organize and structure your tests effectively, manage test data, and generate detailed test reports. Additionally, learning advanced Selenium techniques such as handling dynamic web elements, implementing synchronization strategies, and integrating Selenium with other tools or frameworks can elevate your automation testing capabilities.

Course Schedule

Name Date Details
Testing Courses 23 Nov 2024(Sat-Sun) Weekend Batch View Details
30 Nov 2024(Sat-Sun) Weekend Batch
07 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Senior Associate - Automation and Testing

Akshay Shukla, a senior associate at a multinational company, is an experienced professional with a rich background in cloud computing and software testing. He is proficient in frameworks like Selenium and tools like Cucumber. He also specialises in Test-Driven Development and Behavior-Driven Development.