Taking Screenshots with Selenium WebDriver in Python

 Taking screenshots with Selenium WebDriver in Python 


✅ 1. Basic Screenshot of the Entire Page

python

Copy

Edit

from selenium import webdriver


driver = webdriver.Chrome()  # or Firefox, Edge, etc.

driver.get("https://example.com")


# Take a screenshot

driver.save_screenshot("screenshot.png")  # Saves to current directory


driver.quit()

✅ 2. Screenshot Using get_screenshot_as_file()

python

Copy

Edit

driver.get_screenshot_as_file("screenshot2.png")

Equivalent to save_screenshot().


✅ 3. Screenshot as Bytes or Base64 (e.g., for logging, embedding)

python

Copy

Edit

# As bytes

screenshot_bytes = driver.get_screenshot_as_png()


# As base64 string

screenshot_base64 = driver.get_screenshot_as_base64()

✅ 4. Screenshot of a Specific Element

python

Copy

Edit

from selenium.webdriver.common.by import By


element = driver.find_element(By.ID, "element_id")

element.screenshot("element_screenshot.png")

💡 Only available in recent versions of Selenium (>= 3.141).


🔁 Optional: Wait for Elements to Load (Before Screenshot)

Use WebDriverWait to ensure the page or element is ready:


python

Copy

Edit

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

from selenium.webdriver.common.by import By


WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "element_id")))

driver.save_screenshot("after_wait.png")

📁 Saving to a Custom Folder

python

Copy

Edit

import os


os.makedirs("screenshots", exist_ok=True)

driver.save_screenshot("screenshots/my_screenshot.png")

Let me know if you want to:


Integrate this into a test framework (e.g., unittest or pytest)


Automatically name screenshots by timestamp or test name


Capture full-page screenshots using browser extensions or other tools

Learn Selenium Python Training in Hyderabad

Read More

How to Handle Multiple Browser Tabs or Windows in Selenium

Waits in Selenium: Implicit vs Explicit Waits Explained

Automating Form Filling Using Selenium and Python

Visit Our Quality Thought Training in Hyderabad

Get Directions

Comments

Popular posts from this blog

Understanding Snowflake Editions: Standard, Enterprise, Business Critical

Why Data Science Course?

How To Do Medical Coding Course?