The Katalon Blog

How To Take Screenshot in Selenium?

Written by Huyen Nguyen | Oct 9, 2024, 10:00:00 AM

Taking screenshots during automated testing is an important practice for debugging and reporting purposes. Selenium WebDriver provides built-in functionality to capture screenshots of web pages at any point in the test execution.

Here’s an easy-to-understand and straight-to-the-point guide to taking a screenshot in Selenium.

Make sure you already have the Selenium library installed. If not, refer to the Selenium documentation to set it up.

All good? Let's get going!

Why take screenshot in Selenium?

Automated testing loses much of its value when failures require repeated manual reruns to diagnose what went wrong. A test may fail for many reasons, and without a visual reference, pinpointing the underlying cause becomes unnecessarily time-consuming. A screenshot provides an immediate, reliable snapshot of the browser at the exact moment the issue occurred, helping testers quickly spot broken UI components, unexpected behaviors, or incorrect page states. Screenshots also serve as visual proof that each part of the application behaves according to the expected workflow, making them a key asset for smoother validation and faster debugging.

This is exactly why capturing screenshots in Selenium is so important.

Here are some common situations where taking a screenshot in Selenium becomes essential:

  • When the application behaves unexpectedly
  • When an assertion fails during a test
  • When Selenium struggles to locate web elements
  • When a timeout occurs while waiting for elements to load
  • When you need a clear visual reference to confirm UI behavior

What do you need before taking screenshot in Selenium?

Taking screenshots in Selenium with Python requires a few essential components to be set up beforehand. Here’s what you need before you can start capturing images successfully:

  • Selenium WebDriver: This is the foundation of all browser automation in Python. WebDriver allows you to open pages, interact with elements, perform actions, and ultimately take screenshots. Without initializing a WebDriver instance, no screenshot functionality can be used.
  • save_screenshot() Method: In Python, screenshots are captured using the built-in save_screenshot() method. This method lets you store the current state of the browser window as an image file. It’s simple, reliable, and the standard way to take screenshots using Selenium in Python.
  • webdriver-manager (optional but recommended): Managing browser drivers manually can be tedious. The webdriver-manager library automatically downloads and configures the correct ChromeDriver or GeckoDriver version for you. This ensures your WebDriver setup works smoothly without version mismatches.
  • File Path for Saving the Screenshot: Before taking a screenshot, you need a valid destination path where the image will be stored. Make sure the folder exists and your Python script has permission to write to that directory.
  • Appropriate Browser Driver: Whether you’re using Chrome, Firefox, Edge, or another browser, you must have the corresponding driver installed or managed (e.g., ChromeDriver for Chrome). The driver is what allows Selenium to communicate with the browser.

Once these prerequisites are in place, taking a screenshot in Selenium with Python becomes a straightforward and reliable process.

How does Selenium TakeScreenshot work?

  • Selenium captures the browser’s current state – When a screenshot is triggered, Selenium communicates directly with the browser through the WebDriver API to request an image of whatever is currently rendered on the screen.
  • WebDriver asks the browser driver to take the screenshot – The browser driver (such as ChromeDriver or GeckoDriver) receives the command and handles the low-level work of capturing the visible area of the browser window.
  • The browser driver generates a raw image – The driver collects the pixel data rendered by the browser at that moment and packages it into a standard image format (usually PNG).
  • The image is returned to Selenium – Once captured, the pixel data is passed back through the WebDriver API as an image output, which Selenium then exposes to your script.
  • The script saves the screenshot – Your code decides what to do with the captured image: save it to a file, convert it to base64, log it, or attach it to a report.
  • Screenshot result depends on browser state – Whatever is currently visible on the screen (including pop-ups, errors, overlays, or incomplete page loads) is exactly what Selenium captures.

Guide 1. Take a screenshot in Selenium using Java

To take a screenshot in Java, use the TakesScreenshot interface provided by Selenium.

Java
TakesScreenshot screenshot = (TakesScreenshot) driver; 
File srcFile = screenshot.getScreenshotAs(OutputType.FILE);

Import the necessary libraries:

Java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.OutputType;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils; // Used to save files.

Define the class and main method:

Java
public class ScreenshotExample {
    public static void main(String[] args) {

Set the ChromeDriver path (replace with your actual location):

Java
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");

Initialize the WebDriver:

Java
WebDriver driver = new ChromeDriver();

Here’s the main code that captures a screenshot:

Java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.OutputType;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;

public class ScreenshotExample {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");

        WebDriver driver = new ChromeDriver();

        try {
            driver.get("https://katalon.com/katalon-studio");

            TakesScreenshot screenshot = (TakesScreenshot) driver;
            File srcFile = screenshot.getScreenshotAs(OutputType.FILE);

            File destFile = new File("/path/to/screenshot.png");
            FileUtils.copyFile(srcFile, destFile);

            System.out.println("Screenshot saved successfully!");
        } catch (IOException e) {
            System.out.println("An error occurred while saving the screenshot.");
            e.printStackTrace();
        } finally {
            driver.quit();
        }
    }
}

What’s happening here is:

  1. We use a try block to contain the main logic.
  2. Use driver.get to navigate to the website (katalon.com/katalon-studio)
  3. Take a screenshot using the TakesScreenshot interface.
  4. Specify the output file path: File destFile = new File("/path/to/screenshot.png"); make sure to replace path/to/screenshot with your actual destination.
  5. Use FileUtils to save the captured screenshot.
  6. Add a catch block to handle any IOException that may occur during file operations.
  7. The finally block closes the browser.

Guide 2. Take a screenshot in Selenium using Python

To take a screenshot in Python, use the save_screenshot() method provided by Selenium’s WebDriver API.

Python
driver.save_screenshot("screenshot.png")

Import the necessary libraries:

Python
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager

Define the setup and initialize the WebDriver:

Python
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=Options())

Here’s the main code that captures a screenshot:

Python
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager

service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=Options())

try:
    driver.get("https://katalon.com/katalon-studio")

    screenshot_path = "screenshot.png"
    driver.save_screenshot(screenshot_path)

    print("Screenshot saved successfully!")
finally:
    driver.quit()

What’s happening here is:

  1. We configure the WebDriver service and initialize Chrome.
  2. Use driver.get to navigate to the target webpage (katalon.com/katalon-studio).
  3. Call driver.save_screenshot() to capture and save the screenshot.
  4. Specify your preferred file path using the screenshot_path variable.
  5. The try block ensures the page loads and screenshot is saved.
  6. The finally block closes the browser after execution.

Guide 3. Take Screenshot with Katalon Studio

In the Katalon Studio free version, you have immediate access to a Record-and-Playback feature. Simply perform your manual actions, and Katalon will automatically convert them into an automation script. From there, you can refine the script using Katalon’s extensive keyword library or switch to Scripting mode for maximum flexibility.

Download Katalon To Automate Test Steps Easily

Let’s walk through how to create an automated script that takes a screenshot of a YouTube channel. After installing Katalon Studio, begin by navigating to File > New > Test Case to create a new one.

Give your test case a name:

Next, enter Record-and-Playback mode. Specify the URL you want to record, select a browser, and click “Start” to begin recording.

Now perform your actions—such as navigating, typing a keyword, and selecting a result. Katalon captures each step and converts them into an editable script. For example, the following actions were recorded:

  1. Go to YouTube
  2. Type in “Ted Talk”
  3. Click Search

Here’s the script inside Katalon Studio. You can insert additional keywords by clicking the “Add” button and filling in the Input column. In this example, we added the Take Screenshot keyword and provided the file path where the screenshot will be saved.

Prefer to code for more control? Switch to the Script mode using the tab at the bottom. There, enter the file path where you’d like your screenshot saved. In scripting mode, we added a TakeScreenshot command along with a CloseBrowser command.

The best part? Every object captured during recording is stored inside the Object Repository, which you can reuse across multiple test cases and environments. Your test suites, data files, custom keywords, and even screenshots are neatly organized following the Page Object Model. Here’s what it looks like:

Taking a screenshot is helpful when you want to:

  • Capture the webpage state during test failures
  • Verify UI elements visually
  • Document test progress and results
  • Provide evidence for audits or compliance

Try Screenshot Testing For Free