Capture Screenshot in Selenium

Capture Screenshot in Selenium Python based Automation

Ensuring flawless software functionality, especially with complex GUIs, requires efficient monitoring and evaluation to maintain consistent performance across devices and understand the user impact of errors. Using screenshots in software testing offers valuable visual evidence for identifying issues, confirming UI errors, and ensuring consistency, ultimately speeding up the correction process.

In this blog ,you will learn to capture screenshot in Selenium  Python Based Automation Framework.

Prerequisite: 

  • Python should install on machine ( If Python is not installed then refer this link)
  • PIP library
  • Selenium 

Check Python Version

Windows Command Prompt

Steps to Capture Screenshot in Selenium Python Automation Framework

Code editor: You may choose Code Editor with your choice. Some of them are :
  • PyCharm
  • VS Code

Install selenium ,pytest,webdriver-manager:

  • pip install selenium
  • pip install pytest.
  • pip install webdriver-manager

Selenium : Selenium is an open-source, automated testing tool used to test web applications across various browsers

Pytest : Pytest is a testing framework that allow user to write test codes using python programming language.

Webdriver-Manger : webdriver manager is a library that simplifies the management of webdrivers required for  automated browser testing

Implementation of Code:

Refer below for Fixture Code

import pytest
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By


@pytest.fixture(scope="function")
def web_driver():
    // Instantiate WebDriver 
    driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
    # driver= webdriver.Chrome()
    return driver

def test_home_page(web_driver):
   // Navigate to website
    web_driver.get("https://www.orangetesting.com/")
    // Assert 
    # assert web_driver.title =="Orange Testing"
    web_driver.find_element(By.XPATH,"(//*[@class='dropbt'])[1]").click()
    web_driver.close()

Fixtures are used to feed some data to the tests such as database connections, URLs to test and some sort of input data.

Create a  conftest.py where pass the function name of fixture and put below code in conftest.py

import os
import datetime

def pytest_runtest_makereport(item, call):
    if call.when == 'call' and call.excinfo is not None:
        print("Test failed. Capturing screenshot...")
        driver = item.funcargs.get('web_driver')
        if driver:
            screenshot_dir = "screenshots"
            os.makedirs(screenshot_dir, exist_ok=True)
            now = datetime.datetime.now()
            timestamp = now.strftime("%Y%m%d-%H%M%S")
            test_name = item.name
            screenshot_path = os.path.join(screenshot_dir, f"{test_name}_{timestamp}.png")
            print(f"Saving screenshot to: {screenshot_path}")
            try:
                driver.save_screenshot(screenshot_path)
                print(f"Screenshot saved to {screenshot_path}")
            except Exception as e:
                print(f"Failed to save screenshot: {e}")
Run the code :pytest name of file.py
Benefits of screenshots testing with python
  • Easy to implement
  • Time and Cost efficiency
  • Facilitates with better communication
  • Debugging made easy

Hope this article helps you in learning screenshot capture using Selenium with Python. Still, if you have any doubt then you may contact us on info@thoughtcoders.com

Thought Coders is the independent Software Testing/ Test Automation Company which works on Automation First Strategy. Feel free to contact us if you are looking for Software Testing Services. 

Write A Comment