Skip to main content

Python API Reference

Complete API reference for the Browser7 Python SDK.

Choosing a Client

The SDK provides two clients with identical methods:

from browser7 import Browser7       # Synchronous
from browser7 import AsyncBrowser7 # Asynchronous

Use Browser7 for scripts, notebooks, and blocking contexts. Use AsyncBrowser7 for asyncio-based applications (FastAPI, Django async, etc.). All examples below show the sync client - prefix with await and use AsyncBrowser7 for async usage.


Browser7 (Sync)

Constructor

Browser7(options)

Creates a synchronous Browser7 client.

Parameters:

  • api_key (str, required) - Your Browser7 API key from the Dashboard
  • base_url (str, optional) - Full API base URL including version path. Defaults to 'https://api.browser7.com/v1'

Returns: Browser7 instance

Example:

# Default (production)
client = Browser7(api_key='b7_your_api_key_here')

# Custom regional endpoint
client = Browser7(
api_key='b7_your_api_key_here',
base_url='https://ca-api.browser7.com/v1'
)

Raises:

  • Browser7Error - If api_key is not provided

Context manager:

with Browser7(api_key='b7_your_api_key_here') as client:
result = client.render('https://example.com')
# Connection closed automatically

Methods: close()


AsyncBrowser7 (Async)

Constructor

AsyncBrowser7(options)

Creates an asynchronous Browser7 client. Accepts the same parameters as Browser7.

Example:

client = AsyncBrowser7(api_key='b7_your_api_key_here')
result = await client.render('https://example.com')

Async context manager:

async with AsyncBrowser7(api_key='b7_your_api_key_here') as client:
result = await client.render('https://example.com')
# Connection closed automatically

Methods: aclose() (async equivalent of close())

Async on_progress callbacks: The async client accepts both regular and async callback functions:

async def on_progress(event):
await log_to_db(event) # Awaitable operations supported

result = await client.render('https://example.com', on_progress=on_progress)

Instance Methods

All methods are available on both Browser7 and AsyncBrowser7. Async versions require await.


client.render(url, **options)

Render a URL and automatically poll for the result. This is the recommended method for most use cases.

Parameters:

  • url (str, required) - The URL to render
  • All options below are keyword-only

RenderOptions:

OptionTypeDescriptionDefault
country_codestrCountry code (e.g., 'US', 'GB', 'DE')Auto-select
citystrCity name (e.g., 'new.york', 'london')Auto-select
wait_forlistList of wait actions, max 10 (use wait_for_* helpers)[]
captchastrCAPTCHA mode: 'disabled', 'auto', 'recaptcha_v2', 'recaptcha_v3', 'turnstile''disabled'
block_imagesboolBlock images for faster renderingTrue
fetch_urlslist[str]Additional URLs to fetch after render (max 10)[]
include_screenshotboolEnable screenshot captureFalse
screenshot_formatstrScreenshot format: 'jpeg' or 'png''jpeg'
screenshot_qualityintJPEG quality 1–100 (JPEG only)80
screenshot_full_pageboolCapture full page or viewport onlyFalse
debugboolEnable debug mode: syncs HTML, fetch responses, and screenshots to dashboard for 7 daysFalse
on_progresscallableProgress callback (sync or async)None

Returns: RenderResult

Example:

from browser7 import Browser7, wait_for_click, wait_for_selector

client = Browser7(api_key='b7_your_api_key_here')

result = client.render(
'https://example.com',
country_code='US',
city='new.york',
wait_for=[
wait_for_click('.cookie-accept'),
wait_for_selector('.main-content', state='visible')
],
block_images=True,
on_progress=lambda e: print(f"[{e['type']}] {e.get('status', '')}")
)

Progress Callback:

The on_progress callback receives a dict:

{
'type': 'started' | 'polling' | 'completed' | 'failed',
'renderId': str,
'timestamp': str, # ISO 8601 UTC
'status': str, # Current render status (polling events)
'attempt': int, # Current polling attempt (polling events)
'retryAfter': float # Server-suggested retry interval in seconds
}

Raises:

  • AuthenticationError - Invalid or missing API key (401, 403)
  • ValidationError - Invalid parameters (400)
  • RateLimitError - Too many concurrent requests (429)
  • InsufficientBalanceError - Insufficient account balance (402)
  • RenderError - Render failed or timed out
  • Browser7Error - Network errors or other failures

client.create_render(url, **options)

Create a render job without polling. Use this for manual polling control.

Parameters:

  • url (str, required) - The URL to render
  • Same keyword options as render() except on_progress

Returns: dict with 'renderId'

{'renderId': 'ren_abc123'}

Example:

response = client.create_render('https://example.com', country_code='US')
render_id = response['renderId']
# Poll manually with get_render(render_id)

Raises:

  • AuthenticationError - Invalid or missing API key (401, 403)
  • ValidationError - Invalid parameters (400)
  • RateLimitError - Too many concurrent requests (429)
  • InsufficientBalanceError - Insufficient account balance (402)
  • Browser7Error - Network errors or other failures

client.get_render(render_id)

Get the status and result of a render job. Use this to manually poll for results.

Parameters:

  • render_id (str, required) - The render ID from create_render()

Returns: RenderResult

Example:

import time

response = client.create_render('https://example.com')
render_id = response['renderId']

time.sleep(2)

while True:
result = client.get_render(render_id)

if result.status == 'completed':
print(result.html)
break
elif result.status == 'failed':
raise Exception(f'Render failed: {result.error}')

time.sleep(result.retry_after)

Raises:

  • AuthenticationError - Invalid or missing API key (401, 403)
  • RenderError - Render failed or timed out
  • Browser7Error - Network errors or other failures

client.get_account_balance()

Get the current account balance.

Parameters: None

Returns: AccountBalance

Example:

balance = client.get_account_balance()

print(f'Total: {balance.total_balance_formatted}')
print(f'Renders remaining: {balance.total_balance_cents}')
print(f'Paid: {balance.breakdown["paid"]["formatted"]}')
print(f'Free: {balance.breakdown["free"]["formatted"]}')
print(f'Bonus: {balance.breakdown["bonus"]["formatted"]}')

Raises:

  • AuthenticationError - Invalid or missing API key (401, 403)
  • Browser7Error - Network errors or other failures

client.get_regions()

Get available API regions. Useful for validating region codes or building region-selection UIs.

This is a public endpoint - no API key is required, but the SDK makes the call for you with a consistent interface.

Parameters: None

Returns: RegionsResponse

Example:

response = client.get_regions()

for region in response.regions:
if region.status == 'active':
print(f'{region.code}: {region.name}')

Raises:

  • Browser7Error - Network errors or other failures

Helper Functions

These module-level functions create wait action dictionaries for use with the wait_for parameter.

wait_for_delay(duration)

Create a delay wait action.

Parameters:

  • duration (int, required) - Duration in milliseconds (100–60000)

Example:

from browser7 import wait_for_delay

action = wait_for_delay(3000)
# {'type': 'delay', 'duration': 3000}

wait_for_selector(selector, state, timeout)

Create a selector wait action to wait for a DOM element.

Parameters:

  • selector (str, required) - CSS selector
  • state (str, optional) - Element state: 'visible', 'hidden', or 'attached'. Default: 'visible'
  • timeout (int, optional) - Timeout in milliseconds (1000–60000). Default: 30000

Example:

from browser7 import wait_for_selector

action = wait_for_selector('.main-content', state='visible', timeout=10000)

wait_for_text(text, selector, timeout)

Create a text wait action to wait for specific text content.

Parameters:

  • text (str, required) - Text to wait for
  • selector (str, optional) - CSS selector to limit search scope
  • timeout (int, optional) - Timeout in milliseconds (1000–60000). Default: 30000

Example:

from browser7 import wait_for_text

action = wait_for_text('In Stock', selector='.availability', timeout=10000)

wait_for_click(selector, timeout)

Create a click wait action to click an element (e.g., dismiss cookie banners).

Parameters:

  • selector (str, required) - CSS selector of element to click
  • timeout (int, optional) - Timeout in milliseconds (1000–60000). Default: 30000

Example:

from browser7 import wait_for_click

action = wait_for_click('.cookie-accept', timeout=5000)

Type Definitions

RenderResult

The result returned by render() and get_render().

result.status             # str: 'completed', 'processing', or 'failed'
result.html # str | None: Rendered HTML (automatically decompressed)
result.screenshot # str | None: Base64-encoded image (if include_screenshot=True)
result.load_strategy # str | None: Load strategy used
result.selected_city # dict | None: City used for rendering (see SelectedCity)
result.bandwidth_metrics # dict | None: Network bandwidth statistics (see BandwidthMetrics)
result.captcha # dict | None: CAPTCHA detection and handling info (see CaptchaInfo)
result.timing_breakdown # dict | None: Performance timing breakdown in ms
result.fetch_responses # list | None: Fetch responses (if fetch_urls provided, decompressed)
result.retry_after # float: Server-suggested retry interval in seconds
result.error # str | None: Error message if status is 'failed'

SelectedCity:

result.selected_city = {
'name': 'new.york', # City identifier
'displayName': 'New York', # Human-readable name
'latitude': 40.7128,
'longitude': -74.0060,
'timezoneId': 'America/New_York'
}

BandwidthMetrics:

result.bandwidth_metrics = {
'networkBytes': 1024000, # Bytes downloaded from network
'cachedBytes': 204800, # Bytes served from cache
'cacheHitRate': '16.7%'
}

CaptchaInfo:

result.captcha = {
'detected': True,
'handled': True,
'sitekey': '6Le-...' # Present if CAPTCHA was detected
}

AccountBalance

balance.total_balance_cents      # int: Total balance in cents (1 cent = 1 render)
balance.total_balance_formatted # str: e.g., '$13.00'
balance.breakdown = {
'paid': {'cents': 1200, 'formatted': '$12.00'},
'free': {'cents': 100, 'formatted': '$1.00'},
'bonus': {'cents': 0, 'formatted': '$0.00'},
}

RegionsResponse

response.regions  # list[Region]

Region

region.code    # str: e.g., 'eu', 'ca', 'sg'
region.name # str: e.g., 'Europe'
region.status # str: 'active', 'maintenance', or 'inactive'

Supported Countries

AT, BE, CA, CH, CZ, DE, FR, GB, HR, HU, IT, NL, PL, SK, US

See the Geo-Targeting Guide for available cities within each country.


Error Classes

The SDK provides typed error classes for programmatic error handling. All error classes extend Exception.

Import

from browser7 import (
Browser7Error,
AuthenticationError,
ValidationError,
RateLimitError,
InsufficientBalanceError,
RenderError,
)

Hierarchy

ClassHTTP StatusProperties
Browser7ErrorNetwork errors, 404, 500+message, status_code, body
AuthenticationError401, 403(inherits base)
ValidationError400details
RateLimitError429concurrent_limit
InsufficientBalanceError402(inherits base)
RenderError422, render failureserror_code, render_id, billable

Usage

try:
result = client.render('https://example.com')
except AuthenticationError:
print('Check your API key')
except ValidationError as e:
print(f'Invalid parameters: {e.details}')
except RateLimitError as e:
print(f'Rate limited (max: {e.concurrent_limit})')
except InsufficientBalanceError:
print('Top up your account')
except RenderError as e:
print(f'Render failed: {e.error_code}, billable: {e.billable}')
except Browser7Error as e:
print(f'Other error: {e}')

All error classes extend Browser7Error, which extends Exception. You can catch all SDK errors with except Browser7Error.


Next Steps