Capture Website Screenshots with Python

All, we've released our McAPI Screenshot API on RapidAPI. In this post I'll show you how to capture website screenshots with Python. All sample code will work with the free tier of the API.

Quickstart

Using the requests module to grab a screenshot (replace YOUR_API_KEY with your RapidAPI key). All relevant options are set in the payload string:

# Python 3

import requests

url = 'https://mcapi-screenshot.p.rapidapi.com/'

payload = '{\
  "url": "https://dev.to",\
  "format": "jpeg",\
  "storeExternal": "false",\
  "devices": [ "Default" ]\
}'
headers = {
  'content-type': 'application/json',
  'x-rapidapi-key': 'YOUR_API_KEY',
  'x-rapidapi-host': 'mcapi-screenshot.p.rapidapi.com'
}

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

The response will be in JSON. With storeExternal set to "false", the screenshot is immediately returned as a base64 encoded image (if set to "true" the screenshot is stored in the cloud and the API will return a URL):

{
  "service": "McAPI Screenshot Generator, https://mcapi.io",
  "version": "V1",
  "url": "https://dev.to",
  "screenshots": [
    {
      "device": "Default",
      "screenshot": "data:image/jpeg;base64,/9j/4AAQSkZJRgAB ... 9yXvZG0pSuhyP/9k="
    }
  ]
}

Specifying devices

The API can take multiple screenshot with one REST call, very useful if you want to test website designs against various devices. Simply specify devices like so:

# Python 3

...

payload = '{\
  "url": "https://dev.to",\
  "devices": [ "iPhone 12", "iPhone 12 landscape" ]\
}'

...

More than a hundred devices are predefined but you can also specify your on screen sizes; see docs for more.

Ads and cookie warnings

Other features include a built-in ad blocker and an option to auto-click GDPR cookie banners (currently experimental).

Shown are three screenshots, #1 with default settings:
Screenshot API - Cookie Consent Banner Python
#2 with cookie option set to "true":
Screenshot API - Clicked Cookie Banner and Ad with Python
#3 with cookie and adblock option set to "true":
Screenshot API - Clicked Cookie Banner and Ad Block Python

Try it live

Try the screenshot API on the RapidAPI listing.

More

Reference and more sample code (Python, Ruby, NodeJS, PHP, Swift) on the McAPI screenshot API product page.

The API is currently hosted on AWS Lambda with an API Gateway in front of it. Although over 55MB (zipped) we got it working by installing via S3. Let me know in the comments if you would like a post about this.

20