Take Screenshot Selenium

To take screenshot using Selenium in Python, you can use the save_screenshot() method or get_screenshot_as_file() method. Here’s how you can do it:

Example Code

from selenium import webdriver
from selenium.webdriver.common.by import By

# Initialize the WebDriver (e.g., using Chrome)
driver = webdriver.Chrome()

# Navigate to a website
driver.get("https://www.google.com")

# Take a screenshot and save it as a file
screenshot_path = "google_page.png"
driver.save_screenshot(screenshot_path)
# Or driver.get_screenshot_as_file(screenshot_path)

print(f"Screenshot saved at: {screenshot_path}")

search_field = driver.find_element(By.NAME, "q")

# Take a screenshot of the specific element
search_field.screenshot("search_field.png")

# Close the browser
driver.quit()

Explanation:

  • driver.save_screenshot("filename.png"): Saves a screenshot of the current browser window with the specified filename.
  • element.screenshot("filename.png"): Saves a screenshot of the specific element with the specified filename.
  • You can use any valid file path or name as the argument to save the screenshot where you want.