Python Screenshot API: Capture Website Screenshots

Learn 3 different methods to capture website screenshots with Python - from Selenium to using a simple API.

📋 Table of Contents

Why Capture Screenshots with Python?

Python is one of the most popular languages for automation, web scraping, and data processing. Capturing website screenshots programmatically is essential for:

Method 1: Selenium WebDriver

Selenium is the most popular browser automation tool for Python. It can capture screenshots but requires browser setup.

Installation

pip install selenium webdriver-manager

Basic Screenshot with Selenium

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

def take_screenshot(url, filename):
    # Setup Chrome options
    options = webdriver.ChromeOptions()
    options.add_argument('--headless')
    options.add_argument('--window-size=1920,1080')
    options.add_argument('--no-sandbox')
    
    # Create driver
    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service, options=options)
    
    try:
        driver.get(url)
        driver.save_screenshot(filename)
        print(f"Screenshot saved: {filename}")
    finally:
        driver.quit()

# Usage
take_screenshot('https://example.com', 'screenshot.png')

⚠️ Downsides of Selenium:

Method 2: Playwright for Python

Playwright is a modern alternative to Selenium with better async support and cross-browser testing.

Installation

pip install playwright
playwright install chromium

Basic Screenshot with Playwright

from playwright.sync_api import sync_playwright

def take_screenshot(url, filename):
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        page = browser.new_page(viewport={'width': 1920, 'height': 1080})
        
        page.goto(url, wait_until='networkidle')
        page.screenshot(path=filename, full_page=True)
        
        browser.close()
        print(f"Screenshot saved: {filename}")

# Usage
take_screenshot('https://example.com', 'screenshot.png')

Async Version (For Web Apps)

import asyncio
from playwright.async_api import async_playwright

async def take_screenshot_async(url, filename):
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        page = await browser.new_page(viewport={'width': 1920, 'height': 1080})
        
        await page.goto(url, wait_until='networkidle')
        await page.screenshot(path=filename)
        
        await browser.close()

# Usage
asyncio.run(take_screenshot_async('https://example.com', 'screenshot.png'))

Method 3: Screenshot API (Easiest)

The simplest approach is using a Screenshot API. No browser installation, no dependencies - just a simple HTTP request with Python's requests library.

Installation

pip install requests

Using SnapAPI

import requests

def take_screenshot(url, filename, api_key):
    """Capture a screenshot using SnapAPI"""
    
    api_url = "https://snapapi.alterra-solutions.com/v1/screenshot"
    
    params = {
        'url': url,
        'api_key': api_key,
        'width': 1920,
        'height': 1080,
        'response': 'binary'
    }
    
    response = requests.get(api_url, params=params)
    
    if response.status_code == 200:
        with open(filename, 'wb') as f:
            f.write(response.content)
        print(f"Screenshot saved: {filename}")
    else:
        print(f"Error: {response.status_code}")

# Usage
API_KEY = 'your-api-key-here'
take_screenshot('https://example.com', 'screenshot.png', API_KEY)

✅ Benefits of Screenshot API:

Advanced Options

import requests

def advanced_screenshot(url, api_key, options=None):
    """Capture screenshot with advanced options"""
    
    api_url = "https://snapapi.alterra-solutions.com/v1/screenshot"
    
    params = {
        'url': url,
        'api_key': api_key,
        'response': 'binary',
        'width': options.get('width', 1920),
        'height': options.get('height', 1080),
        'fullpage': options.get('fullpage', False),
        'delay': options.get('delay', 0),  # Wait for JS
        'format': options.get('format', 'png'),
        'device': options.get('device', 'desktop')
    }
    
    response = requests.get(api_url, params=params)
    return response.content if response.ok else None

# Capture full page screenshot
screenshot = advanced_screenshot(
    'https://example.com',
    'your-api-key',
    {
        'fullpage': True,
        'width': 1440,
        'delay': 2000  # Wait 2s for animations
    }
)

with open('fullpage.png', 'wb') as f:
    f.write(screenshot)

Which Method to Choose?

Factor Selenium Playwright Screenshot API
Setup Time 30+ minutes 15 minutes 2 minutes
Dependencies Chrome + Driver Chromium None (just requests)
Memory Usage ~200MB ~150MB Minimal
Serverless Ready ❌ Difficult ⚠️ Complex ✅ Easy
Speed 3-5 seconds 2-3 seconds <2 seconds
Browser Automation ✅ Full control ✅ Full control ❌ Screenshot only

Real-World Examples

Example 1: Batch Screenshot Multiple URLs

import requests
from concurrent.futures import ThreadPoolExecutor

def screenshot_url(args):
    url, api_key, index = args
    api_url = "https://snapapi.alterra-solutions.com/v1/screenshot"
    
    response = requests.get(api_url, params={
        'url': url,
        'api_key': api_key,
        'response': 'binary'
    })
    
    if response.ok:
        filename = f'screenshot_{index}.png'
        with open(filename, 'wb') as f:
            f.write(response.content)
        return f"✅ {url}"
    return f"❌ {url}"

# Batch capture
urls = [
    'https://github.com',
    'https://google.com',
    'https://twitter.com',
    'https://reddit.com'
]

api_key = 'your-api-key'
tasks = [(url, api_key, i) for i, url in enumerate(urls)]

with ThreadPoolExecutor(max_workers=4) as executor:
    results = executor.map(screenshot_url, tasks)
    for result in results:
        print(result)

Example 2: Django View for Thumbnails

from django.http import HttpResponse
import requests

def generate_thumbnail(request):
    url = request.GET.get('url')
    if not url:
        return HttpResponse('URL required', status=400)
    
    api_url = "https://snapapi.alterra-solutions.com/v1/screenshot"
    response = requests.get(api_url, params={
        'url': url,
        'api_key': settings.SNAPAPI_KEY,
        'width': 600,
        'height': 400,
        'response': 'binary'
    })
    
    return HttpResponse(
        response.content,
        content_type='image/png'
    )

Start Capturing Screenshots with Python

Get your free API key and capture 100 screenshots per month.

Get Free API Key →