Let’s take a webpage screenshot with Python. We will be using Python 3.8.10 on Windows 10. Let’s go! 🔥⚡✨
Typical use cases for taking a screenshot of a webpage include information gathering and automated functional or user acceptance testing. First you will need to install the relevant library:
pip install selenium
The selenium library is a simple and popular way to implement software testing using the Selenium Webdriver. The webdriver is used to interface with the web browser. In this example we will be using the geckodriver webdriver to interact with Firefox.
To proceed you need to ensure you have the Firefox browser installed, which you can find HERE. Next, you will need to download the webdriver, which you can find in the Github repo HERE. Find, download and unzip the contents of the geckodriver-v0.31.0-win32.zip file in the repo to the same folder as your Python script. This is the driver that will work for this example on Windows 10. Let’s write our code:
from selenium import webdriver
from time import sleep
driver = webdriver.Firefox(executable_path=r'geckodriver.exe')
driver.get('https://wwe.com')
sleep(1)
driver.get_full_page_screenshot_as_file("wwe.png")
#driver.get_screenshot_as_file("wwe.png") #alternative
driver.quit()
print("SCREENSHOT CAUGHT!")
Let’s explain what is happening here:
- First we import our libraries. We import selenium and the time libraries.
- The method webdriver.Firefox() creates an instance of the Firefox WebDriver. It accepts one parameter which is the geckodriver file we downloaded and unzipped earlier. Recall that this file must exist in the same folder as our Python script for our code to work.
- The driver.get() method will navigate to the URL provided as the parameter. In this case we are going to take a screenshot of wwe.com
- We will sleep our program for 1 second to give the site time to load.
- The driver.get_full_page_screenshot_as_file() will take a full page snapshot of the homepage at the URL we defined in the driver.get() method. It takes one parameter which is the name of the PNG file of the screenshot.
- The method driver.quit() quits the driver and closes the browser window.
When the above code executes we will see a short pause, then the Firefox browser window will open automatically, the site will load and then the window will automatically close and the script will terminate. There should then be a new file named wwe.png in the same folder as your python script.
We hope this helped. Happy coding!👌👌👌