Python Screenshot API code sample

Tested on Python 3.5.2

import sys
import urllib
import requests
import json
import time

apikey = 'YOUR API KEY GOES HERE'

def beginCapture(url,viewport,fullpage,webdriver,javascript):
  serverUrl = "https://api.screenshotapi.io/capture"
  print('Sending request: ' + url)
  headers = { 'apikey': apikey}
  params = {'url': urllib.parse.unquote(url).encode('utf8'), 'viewport': viewport, 'fullpage': fullpage, 'webdriver': webdriver, 'javascript': javascript}
  result = requests.post(serverUrl, data=params, headers=headers)
  print(result.text)
  # {"status":"ready","key":"f469a4c54b4852b046c6f210935679ae"}
  json_results = json.loads(result.text)
  return json_results['key']

def tryRetrieve(key):
  url = 'https://api.screenshotapi.io/retrieve'
  headers = { 'apikey': apikey}
  params = { 'key': key }
  print('Trying to retrieve: ' + url)
  result = requests.get(url, params=params, headers=headers)
  # {"status":"ready","imageUrl":"http://screenshotapi.s3.amazonaws.com/captures/f469a4c54b4852b046c6f210935679ae.png"}
  json_results = json.loads(result.text)
  if json_results["status"] == "ready":
    print('Downloading image: ' + json_results["imageUrl"])
    image_result = requests.get(json_results["imageUrl"])
    return {'success': True, 'bytes': image_result.content}
  else:
    return {'success': False}


if __name__ == "__main__":
  key = beginCapture("http://www.amazon.com","1200x800","true","firefox","true")
  timeout = 30
  tCounter = 0
  tCountIncr = 3

  while True:
    result = tryRetrieve(key)
    if result["success"] :
      print("Saving screenshot to: downloaded_screenshot.png" + key)
      open('downloaded_screenshot.png', 'wb').write(result['bytes'])
      break
    else:
      tCounter += tCountIncr
      print("Screenshot not yet ready.. waiting for: " + str(tCountIncr) + " seconds.")
      time.sleep(tCountIncr)
      if tCounter > timeout:
        print("Timed out while downloading: " + key)
        break