Take a screenshot in Python, using Selenium

Ivan Georgiev
2 min readDec 28, 2021

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:

  1. Open the http://igeorgiev.eu web page.
  2. 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:

--

--