Python SDK

The official Python SDK for RenderScreenshot.

Installation

pip install renderscreenshot

Requirements

  • Python 3.9 or higher

Quick Start

from renderscreenshot import Client, TakeOptions

client = Client('rs_live_xxxxx')

# Take a screenshot
image = client.take(
    TakeOptions.url('https://example.com').preset('og_card')
)

# Save to file
with open('screenshot.png', 'wb') as f:
    f.write(image)

Client

Constructor

from renderscreenshot import Client

client = Client(api_key, base_url=None, timeout=None)
Parameter Type Description
api_key str Your API key (rs_live_* or rs_test_*)
base_url str API base URL (default: https://api.renderscreenshot.com)
timeout float Request timeout in seconds (default: 30.0)

Context Manager

The client can be used as a context manager to automatically close connections:

with Client('rs_live_xxxxx') as client:
    image = client.take(options)

Methods

take(options)

Take a screenshot and return binary data.

image = client.take(
    TakeOptions.url('https://example.com').preset('og_card')
)

# Save to file
with open('screenshot.png', 'wb') as f:
    f.write(image)

Returns: bytes

take_json(options)

Take a screenshot and return JSON metadata.

response = client.take_json(
    TakeOptions.url('https://example.com').preset('og_card')
)

print(response['url'])     # CDN URL
print(response['width'])   # 1200
print(response['height'])  # 630
print(response['cached'])  # True/False

Returns: ScreenshotResponse (TypedDict)

generate_url(options, expires_at)

Generate a signed URL for public embedding.

from datetime import datetime, timedelta

signed_url = client.generate_url(
    TakeOptions.url('https://example.com').preset('og_card'),
    datetime.now() + timedelta(hours=24)  # 24 hours
)

# Use in HTML: <img src="{signed_url}" />

Returns: str

batch(urls, options) / batch(requests)

Process multiple screenshots in a batch.

# Simple batch
results = client.batch(
    ['https://example1.com', 'https://example2.com'],
    TakeOptions.url('').preset('og_card')
)

# Advanced batch with per-URL options
results = client.batch([
    {'url': 'https://example1.com', 'options': {'preset': 'og_card'}},
    {'url': 'https://example2.com', 'options': {'width': 1920}},
])

Returns: BatchResponse (TypedDict)

get_batch(batch_id)

Get the status of a batch job.

status = client.get_batch('batch_abc123')
print(status['completed'], status['total'])

Returns: BatchResponse (TypedDict)

presets() / preset(id)

Get available presets.

presets = client.presets()
og_card = client.preset('og_card')

devices()

Get available device presets.

devices = client.devices()

TakeOptions

Fluent builder for screenshot options.

Creating Options

from renderscreenshot import TakeOptions

# From URL
options = TakeOptions.url('https://example.com')

# From HTML
options = TakeOptions.html('<h1>Hello World</h1>')

# From config dict
options = TakeOptions.from_config({'url': '...', 'width': 1200})

Viewport Options

TakeOptions.url('...') \
    .width(1200)       # Viewport width
    .height(630)       # Viewport height
    .scale(2)          # Device scale factor (1-3)
    .mobile()          # Enable mobile emulation

Capture Options

TakeOptions.url('...') \
    .full_page()       # Capture full scrollable page
    .element('.hero')  # Capture specific element
    .format('png')     # png, jpeg, webp, pdf
    .quality(90)       # JPEG/WebP quality (1-100)

Wait Options

TakeOptions.url('...') \
    .wait_for('networkidle')      # load, networkidle, domcontentloaded
    .delay(2000)                  # Additional delay (ms)
    .wait_for_selector('.loaded') # Wait for selector
    .wait_for_timeout(30000)      # Max wait time (ms)

Presets & Devices

TakeOptions.url('...') \
    .preset('og_card')           # Use a preset
    .device('iphone_14_pro')     # Emulate a device

Content Blocking

TakeOptions.url('...') \
    .block_ads()                  # Block ad networks
    .block_trackers()             # Block analytics
    .block_cookie_banners()       # Auto-dismiss cookie popups
    .block_chat_widgets()         # Block chat widgets
    .block_urls(['*.ads.com/*'])  # Block URL patterns
    .block_resources(['font'])    # Block resource types

Browser Emulation

TakeOptions.url('...') \
    .dark_mode()                  # Enable dark mode
    .reduced_motion()             # Prefer reduced motion
    .media_type('print')          # screen or print
    .user_agent('Custom UA')      # Custom user agent
    .timezone('America/New_York')
    .locale('en-US')
    .geolocation(40.7128, -74.006)

Network Options

TakeOptions.url('...') \
    .headers({'X-Custom': 'value'})
    .cookies([{'name': 'session', 'value': 'abc', 'domain': 'example.com'}])
    .auth_basic('user', 'pass')
    .auth_bearer('token')
    .bypass_csp()

Cache Options

TakeOptions.url('...') \
    .cache_ttl(86400)             # Cache TTL in seconds
    .cache_refresh()              # Force refresh

PDF Options

TakeOptions.url('...') \
    .format('pdf')
    .pdf_paper_size('a4')          # a4, letter, legal, etc.
    .pdf_landscape()
    .pdf_margin('1in')
    .pdf_print_background()
    .pdf_header('<div>Header</div>')
    .pdf_footer('<div>Page <span class="pageNumber"></span></div>')

Storage Options (BYOS)

TakeOptions.url('...') \
    .storage_enabled()
    .storage_path('{year}/{month}/{hash}.{ext}')
    .storage_acl('public-read')

Cache Management

# Get cached screenshot
image = client.cache.get('cache_xyz789')

# Delete single entry
client.cache.delete('cache_xyz789')

# Bulk purge by keys
client.cache.purge(['cache_abc', 'cache_def'])

# Purge by URL pattern
client.cache.purge_url('https://mysite.com/blog/*')

# Purge by date
from datetime import datetime
client.cache.purge_before(datetime(2024, 1, 1))

Webhook Helpers

from renderscreenshot import verify_webhook, parse_webhook

# Verify signature
is_valid = verify_webhook(payload, signature, timestamp, secret)

# Parse event
event = parse_webhook(payload)
if event['type'] == 'screenshot.completed':
    print(event['data']['response']['url'])

Error Handling

from renderscreenshot import Client, TakeOptions, RenderScreenshotError

try:
    client.take(TakeOptions.url('...'))
except RenderScreenshotError as e:
    print(e.http_status)   # 400, 429, etc.
    print(e.code)          # 'invalid_url', 'rate_limited'
    print(e.message)       # Human-readable message
    print(e.retryable)     # True/False
    print(e.retry_after)   # Seconds (for rate limits)

Error Codes

Code HTTP Retryable Description
invalid_request 400 No Malformed request
invalid_url 400 No Invalid URL provided
unauthorized 401 No Invalid API key
forbidden 403 No Access denied
not_found 404 No Resource not found
rate_limited 429 Yes Rate limit exceeded
timeout 408 Yes Screenshot timed out
render_failed 500 Yes Browser rendering failed
internal_error 500 Yes Internal server error

Type Hints

The SDK includes full type hints via py.typed marker and TypedDict definitions:

from renderscreenshot import (
    Client,
    TakeOptions,
    RenderScreenshotError,
    ScreenshotResponse,
    BatchResponse,
    TakeOptionsConfig,
)

Was this page helpful?