How To Save Multiple Screenshots In Selenium Python

In this tutorial, we will learn how to save multiple screenshots using Selenium Python. Saving screenshots can help in the visual verification and debugging of your test automation scripts. Selenium is a popular web automation framework that allows you to control a web browser using Python or other programming languages.

Let’s look at the steps you need to follow to save multiple screenshots while performing browser automation using Selenium and Python.

Prerequisites

Before we proceed, make sure you have the following installed on your machine:

  1. Python: You can download Python from the official website.
  2. Selenium: Install Selenium using the following command: pip install selenium.
  3. Webdriver: Download the appropriate webdriver for your chosen web browser. For this tutorial, we are assuming you are using Google Chrome. Download the ChromeDriver and add it to your system’s PATH.

Step 1: Import required libraries

For this tutorial, we need to import the following libraries:

Step 2: Define a function to save screenshots

Let’s create a function named save_screenshot that accepts two arguments – the webdriver instance and a filename, and saves the screenshot with the given filename.

Step 3: Initialize the webdriver instance

Now, initialize the webdriver instance (Chrome in our case) and set the desired window size for the browser.

Step 4: Use the save_screenshot function

Next, navigate to a webpage, and use the save_screenshot function defined earlier to save multiple screenshots.

Step 5: Clean up

Finally, quit the webdriver instance to close the browser.

Full code

Here’s the complete code for saving multiple screenshots using Selenium and Python:

Expected output

Conclusion

In this tutorial, we learned how to save multiple screenshots in Selenium Python. This is particularly useful in visual verification and debugging, especially when dealing with web applications that involve multiple interactions and dynamic content. With this technique, you can easily save screenshots at different stages of your test automation script and inspect the flow of your tests visually.