Versions used while doing this blog post, (These are the prerequisites to automate chrome browser. Browser and driver versions should match)
selenium python version – 4.5.0
chrome browser version – 105
chrome driver version – 105 (Download link : https://chromedriver.chromium.org/downloads) [download this to a path in project directory]
Screenshot of a webelement can be captured using selenium 4 by following below steps:
1. Instantiate (creation of object) driver object with webdriver.Chrome() (This step opens the chrome browser)
driver = webdriver.Chrome("chromedriver path need to be passed")
2. Now, next steps of maximizing the browser and setting implicit timeout for driver object
driver.implicitly_wait(10)
driver.maximize_window()
3. Launch the expected website URL
driver.get("https://www.google.com")
4. Add an explicit wait that waits till the expected element appears
element = WebDriverWait(driver, 10).until(expected_conditions.visibility_of_element_located((By.CSS_SELECTOR, "img[alt='Google']")))
5. Take the screenshot of the element using screenshot() method [Screenshot will get saved in the same path as that of the code]
element.screenshot("logo.png")
Sample code for reference
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
driver = webdriver.Chrome("/Users/gokul/Personal/Projects/Python/Selenium4ExamplesWithPython/Drivers/chromedriver")
driver.implicitly_wait(10)
driver.maximize_window()
driver.get("https://www.google.com")
element = WebDriverWait(driver, 10).until(expected_conditions.visibility_of_element_located((By.CSS_SELECTOR, "img[alt='Google']")))
element.screenshot("logo.png")
driver.quit()