McAPI - Screenshot API Python

Python sample code to capture website screenshots with the McAPI Screenshot REST API service. All sample code was written in Python 3 but the screenshot API can also be used with older versions. Make sure to install the requests module, e.g. with PIP:

$ python3 -m pip install requests

Requirements: A free RapidAPI account. Replace YOUR_API_KEY in the snippets below with your RapidAPI key.

All samples below work with the free tier of the API, see RapidAPI McAPI Screenshot Listing for available plans.

See the overview page for a reference that lists all available parameters and error codes.

Take a screenshot using Python with requests module

In the first snippet, we take a screenshot of the Indiehackers website. The device is set to Default (=1024x768px). With the storeExternal option set to "false", the screenshot will be returned as a base64 encoded JPEG. See snippet at end of page on how to write base64 encoded images to file with Python.

The source code:

# Python 3
  
import requests

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

payload = '{\
  "url": "https://indiehackers.com",\
  "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 screenshot will be delivered as a JSON object in response.text, e.g.:

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

McAPI Screenshot API - Sample screenshot with Python

The returned image from the Python request:

Image of McAPI Screenshot API Sample Screenshot Python

Specifying devices

The Screenshot API contains a built-in database of over one hundred predefined devices and screen sizes. To get a list of all devices use the listDevices option, like so:

# Python 3
  
...

payload = '{\
  "listDevices": "true",\
}'

...

The API will now return an array of all known devices:

{
  "devices": [

    ...
  
    { "name": "iPhone 12 mini", "width": 375, "height": 812 },
    { "name": "iPhone 12 mini landscape", "width": 812, "height": 375 },
    { "name": "iPhone 12", "width": 390, "height": 844 },
    { "name": "iPhone 12 landscape", "width": 844, "height": 390 },
    { "name": "iPhone 12 Pro", "width": 390, "height": 844 },
    { "name": "iPhone 12 Pro landscape", "width": 844, "height": 390 },
    { "name": "iPhone 12 Pro Max", "width": 428, "height": 926 },
    { "name": "iPhone 12 Pro Max landscape", "width": 926, "height": 428 },

    ...
  ]
}

Internally, the API also maintains proper User Agent-strings for the respective device, those are not shown in the list.

Specifying a predefined device is simple, just use its name in the call:

# Python 3
  
...

payload = '{\
  "url": "https://mcapi.io",\
  "devices": [ "iPhone 12" ]\
}'

...

The devices param is an array; to create multiple screenshots in batch mode, specify additional devices (max. five):

# Python 3
  
...

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

...

Note that specifying multiple devices will cause the API to load the target URL for each device and then take a screenshot; this can take some time with heavy sites; see the discussion on timeouts.

Specifying viewports

If none of the predefined devices and screen sizes are suitable for your application, you can specify your own viewport:

# Python 3
  
...

payload = '{\
  "url": "https://mcapi.io",\
  "viewPort": { "width": 800, "height": 600 }\
}'

...

This will create a screenshot with 800x600px; if a viewport is specified, the API will use a generic desktop User agent-string when loading the target URL.

Note that the viewPort param is ignored if a devices array is also specified.

Taking a screenshot with Python 3 - Handling Cookie consent banners and ad blocking

If so desired, the API can also automatically click the "Accept" (or a similarly worded) button on GDPR / DSGVO cookie consent banners (Note that this feature is experimental for API version V1, discussion.)

Consider this screenshot of the CNBC website with default API settings. The site presents a huge cookie warning:

Screenshot API - Cookie Consent Banner Python

Set the cookie option to "true", like so:

# Python 3
  
...

payload = '{\
  "url": "https://mcapi.io",\
  "cookie": "true",\
  "devices": [ "Default" ]\
}'

...

We can now get the screenshot without the cookie warning:

Screenshot API - Clicked Cookie Banner and Ad with Python

Blocking ads in screenshots

While it can be useful to take screenshots with ads (for example to check ad rotation or placement), usually you will want to block them. The screenshot API comes with a built-in ad blocker, activate it like so:

# Python 3
  
...

payload = '{\
  "url": "https://mcapi.io",\
  "cookie": "true",\
  "adblock": "true",\
  "devices": [ "Default" ]\
}'

...

The website now without cookie warning and without ads:

Screenshot API - Clicked Cookie Banner and Ad blocked Python

The header-parameter - taking screenshots with Python and write to a file

With the storeExternal option set to "false", the screenshot image is returned as a base64 encoded string. Per default, this string is preceded by a header that describes the media type (or MIME) of the string.

Sample data block for a screenshot, to be returned as a PNG:

# Python 3

...

payload = '{\
  "url": "https://mcapi.io",\
  "storeExternal": "false",\
  "format": "png"\
}'

...

The result will look like this:

{
  "service": "McAPI Screenshot Generator, https://mcapi.io",
  "version": "V1",
  "url": "https://mcapi.io",
  "screenshots": [
    {
      "device": "Default",
      "screenshot": "data:image/png;base64,iVBORr/klmpqa2 ... 9yXvZG0pjjmSuhQmCC"
    }
  ]
}

After parsing the result with a JSON parser you can directly set the "screenshot"-string as the src property of an img tag, like so:

# Python 3

import json
...

if response.status_code == 200:
  # In real life you would put the JSON parser in a try/except block 
  # and iterate over the screenshots array
  screenshot = json.loads(response.text)['screenshots'][0]['screenshot']
  print('<img src="' + screenshot + '"/>')
else:
  print("Error")

...

The MIME header will make sure that the image data is interpreted correctly by the browser. However, when writing the image data to a file, including the header would result in a corrupt file. To create a screenshot image without the header, set the header option to "false", like so:

# Python 3

...

payload = '{\
  "url": "https://mcapi.io",\
  "storeExternal": "false",\
  "format": "png",\
  "header": "false"\
}'

...

The returned screenshot image without header:

{
  "service": "McAPI Screenshot Generator, https://mcapi.io",
  "version": "V1",
  "url": "https://mcapi.io",
  "screenshots": [
    {
      "device": "Default",
      "screenshot": "iVBORr/klmpqa2 ... 9yXvZG0pjjmSuhQmCC"
    }
  ]
}

Now, all we have to do is decode the base64 string and then write the screenshot to a file, listed here as a complete Python example:

# Python 3

import requests
import json
import base64

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

payload = '{\
  "url": "https://indiehackers.com",\
  "storeExternal": "false",\
  "format": "png",\
  "header": "false"\
}'
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.encode('utf-8'), headers=headers)

if response.status_code == 200:
  # In real life you would put the JSON parser in a try/except block 
  # and iterate over the screenshots array
  screenshot = json.loads(response.text)['screenshots'][0]['screenshot']
  png = base64.b64decode(screenshot)
  with open('screenshot.png', 'wb') as f:
    f.write(png)
else:
  print("Error")

Back to McAPI Screenshot API main page.