BLACK FRIDAY: Get 50% off your first 3 licenses + 3-months of TestOps with the Bundle offer.
Learn more
All All News Products Insights AI DevOps and CI/CD Community

How To Take Screenshot in Selenium?

Learn how to take screenshots in Selenium with this comprehensive guide. Capture screenshots for test automation and debugging efficiently.

Hero Banner
Smart Summary

Capturing visual evidence during automated testing is essential for debugging, verifying UI, and documenting test outcomes. This guide details how to efficiently capture screenshots in Selenium using Java, Python, and Katalon Studio, ensuring a clear visual record of your application's state at critical moments.

  • Implement Java Screenshots: Utilize the `TakesScreenshot` interface and `getScreenshotAs(OutputType.FILE)` method, saving the image to a specified file via `FileUtils.copyFile()`, all within a try-catch-finally block for robust error handling and browser closure.
  • Streamline Python Screenshots: Employ the `driver.save_screenshot()` method for direct capture and leverage `webdriver-manager` for simplified driver setup, efficiently storing images to a designated file path.
  • Leverage Katalon Studio: Utilize its Record-and-Playback feature to automatically generate scripts with screenshot capture, and enhance flexibility by integrating keywords or writing custom scripts with object management in the reusable Object Repository.
Good response
Bad response
|
Copied
>
Read more
Blog / Insights /
How To Take Screenshot in Selenium?

How To Take Screenshot in Selenium?

Contributors Updated on

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 (https://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 (https://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.

Create a new test case in Katalon Studio

Give your test case a name:

Name a test case in Katalon Studio

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

Record and playback feature in Katalon Studio

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

Automate screenshot with Katalon Studio

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.

Use Katalon Studio to take screenshot in Selenium

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.

Scripting mode in Katalon Studio

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:

Object Repository in Katalon Studio

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

Explain

|

FAQs

Why should I take screenshots during Selenium tests?

+

Screenshots help you debug failures, verify UI state, document test results, and provide evidence for audits/compliance—especially when a test fails intermittently or the UI is dynamic.

 

How do I take a screenshot in Selenium using Java?

+

Use Selenium’s TakesScreenshot interface:

  • Cast the driver to TakesScreenshot

  • Call getScreenshotAs(OutputType.FILE)

  • Copy the file to your target path (commonly with FileUtils.copyFile)
    This is typically wrapped in try/catch/finally to handle IO errors and ensure the browser closes.

How do I take a screenshot in Selenium using Python?

+

Use the built-in method:

  • driver.save_screenshot("/your/path/screenshot.png")
    Many teams pair this with webdriver-manager so ChromeDriver versioning is handled automatically.

How can I capture screenshots using Katalon Studio (Selenium-based) without heavy coding?

+

You can:

  • Record & Playback your actions to generate steps automatically

  • Add the “Take Screenshot” keyword into the test case and provide a save path

  • Optionally switch to Scripting mode for more control
    Captured objects are saved to the Object Repository for reuse across tests.

What are common best practices for screenshot capture in UI automation?

+

  • Capture screenshots on failure (and optionally at key checkpoints).

  • Use unique filenames (include test name + timestamp).

  • Save to a known artifacts folder so CI/CD can archive it.

  • Pair screenshots with logs (and video/HTML snapshot if available) for faster triage.

  • Avoid hardcoding OS-specific paths when running in CI (use env vars or relative paths).

Katalon Team
Katalon Team
Contributors
The Katalon Team is composed of a diverse group of dedicated professionals, including subject matter experts with deep domain knowledge, experienced technical writers skilled, and QA specialists who bring a practical, real-world perspective. Together, they contribute to the Katalon Blog, delivering high-quality, insightful articles that empower users to make the most of Katalon’s tools and stay updated on the latest trends in test automation and software quality.
Click