Capture Website Screenshot using Python

Bhakti Jain Avatar

·

Working with different tools, might be a confusing task sometime, and what is better than getting your work done in your favorite programming language.
So, here is the guide in which we’re diving into the world of development with Python. Capturing website screenshots – a fundamental aspect of web interaction and analysis – through the lens of Python programming. Now you can capture screenshots of any website using our application HTML to Img in any IDE of your choice with a simple Python Script.

How to generate the API Key

To get the API Token, you can register for a free account on the below link –

HTMLCSSToImg

The link will land you to the login/registration page.

If you already have an account, you can simply login, otherwise register for a free account.

Once you logged in successfully, you will see the generated API Key at the top left corner that you can use for Authentication.

Our app also allows you to regenerate the API Keys whenever you are willing to.

Capturing Screenshots using Python Script

In Python, we have requests and json modules, which are necessary for making HTTP requests and handling JSON data, respectively.

We will be using Dictionary data structure to store the jSON objects to make the API request alon with the essential Headers.

Below is the python code to capture the screenshot of any website of your choice simply by passing its URL and API Key.

import requests
import json

url = "<URL OF THE WEBSITE WHOSE SCREENSHOT IS TO BE CAPTURED>"

payload = json.dumps({
  "url": "https://htmlcsstoimg.com",
  "generate_img_url": True,
  "viewPortWidth": 540,
  "viewPortHeight": 360,
  "full_page": True,
  "wait_till": 1
})
headers = {
  'CLIENT-API-KEY': '<YOUR API KEY>',
  'Connection': 'keep alive',
  'Content-Type': 'application/json',
  'Accept-Encoding': 'gzip, deflate, br'
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)

Add the URL of the website as the value to the “url” key and replace <YOUR API KEY> with the API key you have generated
Note : You can use any editor or IDE of your choice to run the above script.

On running the Python code, you will get the URL of the captured screenshot in the output.

In conclusion, capturing website screenshots with Python is an exciting endeavor that offers endless possibilities for developers and enthusiasts alike. So whether you’re new to python or a pro, you can harness the power of this simple Python Script for all your website screenshot needs.