ScreenshotsAPI Docs

Bulk Screenshots

Take multiple screenshots efficiently using the API

Bulk Screenshots

While the Screenshots API doesn't directly support bulk operations, you can efficiently capture multiple web pages by implementing a batching system. This guide shows you how to handle multiple screenshot requests in a controlled and efficient manner.

The recommended way to handle multiple screenshots is to process them in batches. This approach:

  1. Prevents overwhelming the API
  2. Provides better error handling
  3. Allows for progress tracking
  4. Maintains rate limits

Here's a comprehensive implementation that you can use:

/**
 * Process a list of URLs in batches, taking screenshots via API
 * @param {string[]} urls - Array of URLs to screenshot
 * @param {number} batchSize - Number of concurrent requests (default: 25)
 * @param {Object} options - Screenshot API options
 * @returns {Promise<Array>} - Results from all API calls
 */
async function processScreenshotBatches(urls, batchSize = 25, options = {}) {
  // Default API options
  const defaultOptions = {
    fmt: 'png',
    qual: 80,
    full: false,
    ads: true,
    cookie: true,
    track: true,
    wait: 0,
    clear: true,
    device: 'desktop',
    dark: false,
    width: 1920,
    height: 1080,
    scale: 1,
    mobile: false,
    touch: false,
    land: true,
    load: 'networkidle',
    timeout: 120,
    trans: false,
    key: '' // TODO: Add your API key here
  };
 
  // Merge default options with any provided options
  const apiOptions = { ...defaultOptions, ...options };
  
  // Results array to store all responses
  const results = [];
  
  // Process URLs in batches
  for (let i = 0; i < urls.length; i += batchSize) {
    console.log(`Processing batch ${i/batchSize + 1} of ${Math.ceil(urls.length/batchSize)}`);
    
    // Get current batch of URLs
    const batch = urls.slice(i, i + batchSize);
    
    // Create array of promises for current batch
    const batchPromises = batch.map(url => {
      return fetchScreenshot(url, apiOptions);
    });
    
    // Wait for all promises in current batch to resolve
    const batchResults = await Promise.all(batchPromises);
    
    // Add batch results to overall results
    results.push(...batchResults);
    
    // Optional: Add a small delay between batches to avoid overwhelming the API
    if (i + batchSize < urls.length) {
      await new Promise(resolve => setTimeout(resolve, 1000));
    }
  }
  
  return results;
}
 
/**
 * Fetch a screenshot for a single URL
 * @param {string} url - URL to screenshot
 * @param {Object} options - API options
 * @returns {Promise<Object>} - API response
 */
async function fetchScreenshot(url, options) {
  try {
    // Create a copy of options to avoid modifying the original
    const requestOptions = { ...options };
    
    // Add the URL parameter separately (don't double-encode)
    const params = new URLSearchParams();
    params.append('url', url);
    
    // Add all other options
    for (const [key, value] of Object.entries(requestOptions)) {
      params.append(key, value);
    }
    
    // Make API request
    const apiUrl = `https://api.screenshotsapi.dev/take?${params.toString()}`;
    console.log(`Fetching: ${apiUrl}`);
    
    const response = await fetch(apiUrl);
    
    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`API error: ${response.status} ${response.statusText} - ${errorText}`);
    }
    
    const data = await response.json();
    return {
      url,
      success: true,
      data
    };
  } catch (error) {
    console.error(`Error fetching screenshot for ${url}:`, error);
    return {
      url,
      success: false,
      error: error.message
    };
  }
}
 
// Example usage
async function main() {
  // Example list of URLs (you would replace this with your actual list of URLs)
  const urlsToProcess = [
    'https://sitelifter.com',
    'https://google.com',
    'https://github.com',
    // ... more URLs
  ];
  
  // Process URLs in batches of 25
  const results = await processScreenshotBatches(urlsToProcess);
  
  console.log(`Processed ${results.length} URLs`);
  console.log(`Successful: ${results.filter(r => r.success).length}`);
  console.log(`Failed: ${results.filter(r => !r.success).length}`);
 
  console.log(results);
  
  // Do something with the results
  return results;
}
 
// Export functions for use in other modules
module.exports = {
  processScreenshotBatches,
  fetchScreenshot
};

Key Features of This Implementation

  1. Batch Processing:

    • Processes URLs in configurable batch sizes
    • Prevents overwhelming the API
    • Includes optional delay between batches
  2. Error Handling:

    • Comprehensive error catching and reporting
    • Continues processing even if some requests fail
    • Provides detailed error information
  3. Progress Tracking:

    • Logs batch progress
    • Tracks successful and failed requests
    • Provides summary statistics
  4. Flexibility:

    • Configurable batch size
    • Customizable API options
    • Easy to integrate into existing systems

Best Practices

  1. Rate Limiting:

    • Start with a small batch size (e.g., 25)
    • Monitor API responses
    • Adjust batch size based on performance
  2. Error Handling:

    • Implement proper error logging
    • Consider retry logic for failed requests
    • Store results for later analysis
  3. Performance:

    • Use appropriate timeouts
    • Monitor memory usage
    • Consider implementing a queue system for very large batches
  4. Security:

    • Keep your API key secure
    • Validate input URLs
    • Implement proper error handling

Example Usage

// Import the functions
const { processScreenshotBatches } = require('./screenshot-batch');
 
// Your list of URLs
const urls = [
  'https://example1.com',
  'https://example2.com',
  // ... more URLs
];
 
// Process with custom options
processScreenshotBatches(urls, 25, {
  fmt: 'png',
  qual: 90,
  // ... other options
})
.then(results => {
  // Handle results
  console.log('Processing complete');
})
.catch(error => {
  console.error('Error processing batches:', error);
});

Webhook Payload

For each screenshot in your bulk request, you'll receive a webhook with:

{
  "message": "Screenshot captured successfully",
  "url": "https://production-screenshots-api-dev.s3.amazonaws.com/screenshot-sitelifter-com-2025-04-29T01:27:52.816Z.png",
  "timestamp": "2025-04-29T01:27:52.816Z",
  "duration": 17799
}

Monitoring Progress

To track the progress of your bulk requests:

  1. Store request IDs when initiating screenshots
  2. Record webhook responses in your database
  3. Implement a status endpoint to check progress
  4. Set up alerts for failed requests

Common Use Cases

  1. Website Monitoring: Capture regular screenshots of multiple pages
  2. Competitor Analysis: Track changes across multiple websites
  3. Content Archiving: Preserve web content for future reference
  4. Quality Assurance: Verify website appearance across different pages

On this page