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:
- Selenium Features
- Selenium Installation
- Selenium Locators
- XPath Fundamentals
- CSS Selectors Methods
- Different Browsers Execution
- find_element & find_elements
- Check Enabled Status
- Check Displayed Status
- Check Selected Status
- Selenium Waits
- Send_keys Method
- Click Method
- Get Text
- Get Attribute Value
- Get Current URL
- Forward, Back, Refresh
- Take Screenshot
- Handle Browser Tabs
- Handle iframe
- Mouse Hover
- Context-Click
- Drag & Drop
- Handle Alerts
- Handle Dropdown
- Execute Javascript
- Scroll To element
- Headless Mode Execution
- Chrome Options
- Keyboard Action
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.