Last updated on November 6th, 2024 at 12:23 pm
This tutorial provides a concise guide on how to capture a screenshot of a website using the Selenium package. Prior to starting, it is necessary to install Selenium via pip. There are several methods available for obtaining a screenshot of any website with Python Selenium. We will explore some of the practical options that are suitable for various use cases. You may select any of the functions listed below according to your specific needs.
Table of Contents
- What is Selenium?
- Screenshot part of Webpage
- Complete page Screenshot
- Get only the viewport window
- Get base64 encoded screenshot
What is Selenium?
In simple terms. Selenium provides an API to access web browsers like Chrome, IE, Edge, Firefox, Safari etc., using Selenium WebDriver. You can write acceptance tests using this and it’s very handy to automate some of the website testing workflows. The Selenium version I am using is 4.7.2. . More details on Selenium can be found in this readme documentation.
Installing Selenium
pip3 install selenium
Note: If you get a command not found for pip3 then try using just the pip command. In case if you don’t gave pip, check this document to install it first https://pip.pypa.io/en/stable/installation/
Screenshot part of Webpage
I am going to use python.org website as an example. In order to get the screenshot of a specific section within the webpage and save it as a png file, we can use screenshot_as_png.
#!/usr/local/bin/python3
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('https://python.org')
main_nav = driver.find_element("id","mainnav")
screenshot=main_nav.screenshot_as_png
with open('main_nav.png', 'wb') as f:
f.write(screenshot)
driver.quit()
When you run the code above it basically finds the element with id=mainnav and just takes the screenshot of that element in web page. Make sure to replace this with any element with the webpage you would like to screenshot.

Complete page Screenshot
To get the full page screenshot all you have to do is save_full_page_screenshot
#!/usr/local/bin/python3
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('https://python.org')
driver.save_full_page_screenshot('fullpage.png')
driver.quit()
Get only the viewport window
To get the webpage viewable within a browser window then use the save_screenshot function
#!/usr/local/bin/python3
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('https://python.org')
driver.save_screenshot('viewport.png')
driver.quit()

Get base64 encoded screenshot
To save base64 encoded string of full webpage use get_full_page_screenshot_as_base64(). I saved the below script in a file named base_64.py
#!/usr/local/bin/python3
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('https://python.org')
print(driver.get_full_page_screenshot_as_base64())
driver.quit()

Note: Modify shebang as per your Python binary location