Take a screenshot in Python, using Selenium
Selenium driver has save_screenshot()
method which saves a screenshot of the browser viewable area to an image file. Let’s try taking a screenshot by example:
- Open the http://igeorgiev.eu web page.
- Save a screenshot from the page to a file.
URL = "https://igeorgiev.eu"
with contextlib.closing(webdriver.Chrome()) as driver:
driver.get(URL)
driver.save_screenshot(str(SCREENSHOTS_DIR / "igeorgiev-home.png"))
The contextlib.closing
context manager is calling the webdriver’s close()
method when the code block is exited. This will close the browser page.
Here is the screenshot saved by Selemium for me:
You can save also a screenshot of an element:
URL = "https://igeorgiev.eu"
with contextlib.closing(webdriver.Chrome()) as driver:
driver.get(URL)
content = driver.find_element(By.CSS_SELECTOR, ".md-content")
content.screenshot(str(SCREENSHOTS_DIR / "igeorgiev-content.png"))
And the screenshot of the element looks like:
The built-in methods provided by Selenium save only the visible part of the web page or an element. If you need to get a screenshot of the entire webpage or an element, you could use the Selenium-Screenshot package.
More information
You can get more information:
- Selenium TakeScreenshot from the official Selenium documentation.
- Selenium-Screenshot — take screenshots from entire webpage or element.
- Web Tests with Selenium at Python-Refs