Skip to main content

Python Examples

Copy-paste ready examples for common use cases with the Browser7 Python SDK.

All examples are shown in both sync and async versions. Sync uses Browser7, async uses AsyncBrowser7 with await.


Basic Examples

Simple Page Render

# Sync
from browser7 import Browser7

client = Browser7(api_key='b7_your_api_key_here')
result = client.render('https://example.com')
print(result.html)
# Async
import asyncio
from browser7 import AsyncBrowser7

async def main():
client = AsyncBrowser7(api_key='b7_your_api_key_here')
result = await client.render('https://example.com')
print(result.html)

asyncio.run(main())

Geo-Targeted Render

# Sync - target a specific country
result = client.render('https://example.com', country_code='DE')

# Sync - target a specific city
result = client.render('https://example.com', country_code='US', city='new.york')

# Async
result = await client.render('https://example.com', country_code='GB', city='london')

Screenshot Capture

# Viewport screenshot (JPEG, default)
result = client.render(
'https://example.com',
include_screenshot=True
)

# Full page PNG screenshot
result = client.render(
'https://example.com',
include_screenshot=True,
screenshot_format='png',
screenshot_full_page=True
)

# Save to file
import base64

with open('screenshot.png', 'wb') as f:
f.write(base64.b64decode(result.screenshot))

Wait Actions

Wait for Element Visibility

from browser7 import Browser7, wait_for_selector

client = Browser7(api_key='b7_your_api_key_here')

result = client.render(
'https://example.com',
wait_for=[
wait_for_selector('.product-loaded', state='visible', timeout=15000)
]
)
from browser7 import wait_for_click, wait_for_selector

result = client.render(
'https://example.com',
wait_for=[
wait_for_click('.cookie-accept', timeout=5000),
wait_for_selector('.main-content', state='visible')
]
)

Wait for Text Content

from browser7 import wait_for_text

result = client.render(
'https://shop.example.com/product/123',
wait_for=[
wait_for_text('In Stock', selector='.availability', timeout=10000)
]
)

Multiple Wait Actions Combined

from browser7 import wait_for_click, wait_for_delay, wait_for_selector, wait_for_text

result = client.render(
'https://example.com',
wait_for=[
wait_for_click('.cookie-banner-accept', timeout=5000),
wait_for_selector('.content', state='visible'),
wait_for_text('Data loaded'),
wait_for_delay(500)
]
)

CAPTCHA Solving

Auto-Detect and Solve

result = client.render(
'https://example.com',
captcha='auto'
)

Target a Specific CAPTCHA Type

# reCAPTCHA v2
result = client.render('https://example.com', captcha='recaptcha_v2')

# reCAPTCHA v3
result = client.render('https://example.com', captcha='recaptcha_v3')

# Cloudflare Turnstile
result = client.render('https://example.com', captcha='turnstile')

Two-Step CAPTCHA Detection

Check for a CAPTCHA first, then solve only if needed:

# First render - no CAPTCHA solving (fastest)
result = client.render('https://example.com')

# Check if CAPTCHA was present
if result.captcha and result.captcha.get('detected') and not result.captcha.get('handled'):
# Re-render with auto CAPTCHA solving
result = client.render('https://example.com', captcha='auto')

Advanced Usage

Progress Tracking (Sync)

def on_progress(event):
event_type = event['type']
if event_type == 'started':
print(f"Render started: {event['renderId']}")
elif event_type == 'polling':
print(f"Polling attempt {event['attempt']}: {event['status']}")
elif event_type == 'completed':
print('Render completed')
elif event_type == 'failed':
print('Render failed')

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

Progress Tracking (Async)

The async client supports both sync and async callbacks:

# Async callback with awaitable operations
async def on_progress(event):
print(f"[{event['type']}] {event.get('status', '')}")
await save_progress_to_db(event)

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

Manual Polling (Low-Level API)

import time

# Create the render job
response = client.create_render('https://example.com', country_code='US')
render_id = response['renderId']
print(f'Render ID: {render_id}')

time.sleep(2)

# Poll manually
for attempt in range(60):
result = client.get_render(render_id)
print(f'Attempt {attempt + 1}: {result.status}')

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

time.sleep(result.retry_after)

Manual Polling (Async)

import asyncio

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

await asyncio.sleep(2)

for attempt in range(60):
result = await client.get_render(render_id)

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

await asyncio.sleep(result.retry_after)

Error Handling with Retries

import time
from browser7 import Browser7, AuthenticationError, ValidationError, RenderError

def render_with_retry(client, url, max_retries=3, **options):
for attempt in range(max_retries):
try:
return client.render(url, **options)
except AuthenticationError:
raise # Don't retry auth errors - fix your API key
except ValidationError:
raise # Don't retry validation errors - fix your request
except Exception as e:
if attempt == max_retries - 1:
raise
wait = 2 ** attempt # Exponential backoff: 1s, 2s, 4s
print(f'Attempt {attempt + 1} failed: {e}. Retrying in {wait}s...')
time.sleep(wait)

result = render_with_retry(client, 'https://example.com', country_code='US')

Batch Processing (Sequential)

urls = [
'https://example.com/page1',
'https://example.com/page2',
'https://example.com/page3',
]

results = []
for url in urls:
try:
result = client.render(url)
results.append({'url': url, 'html': result.html})
except Exception as e:
results.append({'url': url, 'error': str(e)})

print(f'Scraped {len(results)} pages')

Batch Processing (Async + Concurrent)

import asyncio
from browser7 import AsyncBrowser7

async def scrape_all(urls, max_concurrent=5):
semaphore = asyncio.Semaphore(max_concurrent)

async def scrape_one(client, url):
async with semaphore:
try:
result = await client.render(url)
return {'url': url, 'html': result.html}
except Exception as e:
return {'url': url, 'error': str(e)}

async with AsyncBrowser7(api_key='b7_your_api_key_here') as client:
tasks = [scrape_one(client, url) for url in urls]
return await asyncio.gather(*tasks)

urls = [
'https://example.com/page1',
'https://example.com/page2',
'https://example.com/page3',
]

results = asyncio.run(scrape_all(urls))

Fetch Additional URLs

result = client.render(
'https://example.com',
fetch_urls=[
'https://api.example.com/data.json',
'https://example.com/config.json',
]
)

# Access fetch responses
for response in result.fetch_responses:
print(response)

Account Operations

Check Account Balance

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"]}')

Check Balance Before Expensive Operations

balance = client.get_account_balance()

if balance.total_balance_cents < len(urls):
raise Exception(f'Insufficient balance: {balance.total_balance_formatted}')

# Proceed with batch render
for url in urls:
result = client.render(url)

Available Regions

response = client.get_regions()

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

Real-World Scenarios

E-Commerce Product Scraping

from browser7 import Browser7, wait_for_selector
import base64

client = Browser7(api_key='b7_your_api_key_here')

result = client.render(
'https://shop.example.com/product/123',
country_code='US',
city='new.york',
wait_for=[
wait_for_selector('.product-price', state='visible'),
wait_for_selector('.stock-status', state='visible'),
],
include_screenshot=True,
screenshot_format='jpeg',
screenshot_quality=85
)

# Save screenshot
with open('product.jpg', 'wb') as f:
f.write(base64.b64decode(result.screenshot))

print(result.html)

Async FastAPI Scraping Endpoint

from fastapi import FastAPI, HTTPException
from browser7 import AsyncBrowser7, wait_for_selector

app = FastAPI()
client = AsyncBrowser7(api_key='b7_your_api_key_here')

@app.get('/scrape')
async def scrape(url: str, country: str = 'US'):
try:
result = await client.render(
url,
country_code=country,
wait_for=[wait_for_selector('body', state='visible')],
)
return {'html': result.html, 'city': result.selected_city}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))

News Article with Cookie Handling

from browser7 import Browser7, wait_for_click, wait_for_selector

client = Browser7(api_key='b7_your_api_key_here')

result = client.render(
'https://news.example.com/article/123',
wait_for=[
wait_for_click('.gdpr-accept-all', timeout=5000),
wait_for_selector('article.content', state='visible', timeout=15000),
],
block_images=True # Faster for text content
)

print(result.html)

Protected Site with CAPTCHA

result = client.render(
'https://protected.example.com/data',
captcha='auto',
country_code='US',
wait_for=[
wait_for_selector('.data-table', state='visible', timeout=30000)
]
)

Best Practices

Performance

# Block images when you only need HTML (default: True, but worth being explicit)
result = client.render('https://example.com', block_images=True)

# Use specific CAPTCHA types instead of 'auto' when you know the type
# (avoids 10-second polling, single check only)
result = client.render('https://example.com', captcha='recaptcha_v2')

# Use viewport-only screenshots unless you need the full page
result = client.render(
'https://example.com',
include_screenshot=True,
screenshot_full_page=False # Default - faster
)

Connection Management

# For long-running scripts, use a context manager to ensure cleanup
with Browser7(api_key='b7_your_api_key_here') as client:
for url in urls:
result = client.render(url)
process(result)

# Or call close() explicitly
client = Browser7(api_key='b7_your_api_key_here')
try:
result = client.render('https://example.com')
finally:
client.close()

Next Steps