To take a screenshot using Selenium in Python, you can use the get_screenshot_as_file() method provided by the WebDriver class. Here’s an example:
from selenium import webdriver # Create a new instance of the Chrome driver driver = webdriver.Chrome() # Navigate to a webpage driver.get("https://codetryout.com/selenium-take-screenshot-python/") # Take a screenshot and save it to a file driver.get_screenshot_as_file("screenshot.png") # Close the browser driver.quit()
In the above example, we do the following
- first import the webdriver module from the Selenium package.
- Then, we create a new instance of the Chrome driver.
- Next, we navigate to a webpage using the get() method, passing the URL of the desired page.
- After that, we call the get_screenshot_as_file() method on the driver object, specifying the file name where we want to save the screenshot (in this case, “screenshot.png”).
- Finally, we close the browser using the quit() method to release system resources.
Make sure you have installed the Selenium library and the appropriate web driver for your chosen browser (e.g., Chrome driver for Google Chrome). You can find the Chrome driver and installation instructions on the official Selenium website: https://sites.google.com/a/chromium.org/chromedriver/