This is a quick tutorial on capturing website screenshot.We are using the Selenium package for this. Before we begin you have to install selenium using pip. There are multiple methods to get a screenshot of any website using Python Selenium. We are going through some of the available options which are handy for most use cases. Use any of the below functions as per your requirement.

Table of Contents

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

Leave a Reply

Your email address will not be published. Required fields are marked *