How To Take Screenshot In Headless Browser In Selenium Python

In this tutorial, we will learn how to take a screenshot in a headless browser using Selenium Python. This is particularly useful for automated testing, debugging, and web scraping purposes when there is no need to render the browser UI. We will be using the Selenium WebDriver library and the Google Chrome browser with the ChromeDriver executable.

Step 1: Install Selenium and Download ChromeDriver

First, you need to install the Selenium library using pip:

Next, download the appropriate version of ChromeDriver for your system from the following link: https://sites.google.com/chromium.org/driver/

Unzip the downloaded file and save the chromedriver executable to a location on your system.

Step 2: Configure the Headless Browser

To take a screenshot in a headless browser, we need to create an instance of the WebDriver with the --headless argument. This will run the browser without any user interface. Here’s how to create a headless Chrome instance using Python:

Replace "path/to/chromedriver" with the actual path of the chromedriver executable on your system.

Step 3: Navigate to the Desired Page

Now, use the get() method to navigate to the desired webpage:

Replace https://www.example.com with the URL of the page, you’d like to capture.

Step 4: Take the Screenshot

To take a screenshot of the current page, use the save_screenshot() method:

This will save a screenshot of the entire webpage in the same directory as your script, with the file name “screenshot.png”.

Step 5: Close the Driver

After taking the screenshot, it’s a good practice to close the driver to free up resources:

Full Code

Output

Conclusion

With just a few lines of code, we were able to take a screenshot of a webpage in a headless browser using Selenium and Python. This can be used for various purposes such as automated testing, debugging, or web scraping. Remember to always close the driver after you’re finished to free up resources and prevent potential issues.