Allscreenshots
Sign inGet an API key
Blog

Tutorial

Introduction to Puppeteer for Browser Automation

Alex Chen6 min read

Puppeteer gives you programmatic control over Chrome and Firefox through a clean Node.js API. Built by the Chrome DevTools team at Google, it's designed for tasks where you need direct browser manipulation: automated testing, web scraping, PDF generation, and screenshot capture.

What Makes Puppeteer Different

Unlike Selenium, which abstracts across many browsers through WebDriver, Puppeteer communicates with browsers through modern automation protocols. Chrome uses the Chrome DevTools Protocol (CDP) by default, while Firefox uses WebDriver BiDi by default. This direct connection gives Puppeteer access to low-level browser features such as network events, console logs, tracing, screenshots, and PDF generation.

The trade-off is still browser scope. Puppeteer is strongest for Chrome-first automation and now supports Firefox for production browser automation use cases, but it does not target Safari. If you need Safari/WebKit coverage, compare Puppeteer with Playwright before choosing your test stack.

Key capabilities:

  1. Headless by default: Runs without a visible UI, perfect for CI
  2. Full page interaction: Click, type, scroll, drag-and-drop
  3. Network interception: Mock API responses, block resources
  4. Performance tracing: Capture Chrome DevTools timeline data
  5. PDF and screenshot generation: Built-in, high-quality output

Getting Started

Install Puppeteer in any Node.js project:

bash
npm install puppeteer

Here's a minimal script that navigates to a page and takes a screenshot:

javascript
const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://example.com'); await page.screenshot({ path: 'example.png' }); await browser.close(); })();

Run it with node script.js and you'll have a screenshot in your directory. That's the entire setup.

Core Concepts

Puppeteer organizes around a few key objects:

ObjectPurpose
BrowserA browser instance (Chromium or Firefox)
BrowserContextAn isolated session, like an incognito window
PageA single tab, where most interaction happens
FrameAn iframe within a page
ElementHandleA reference to a DOM element

Most of your code will work with Page. You'll create a browser, open a page, do your work, then close the browser.

javascript
const browser = await puppeteer.launch(); const page = await browser.newPage(); // Your automation code here await browser.close();

Finding and Interacting With Elements

Puppeteer uses CSS selectors and XPath for element location. The API feels natural if you've used document.querySelector:

javascript
// Click a button await page.click('#submit-button'); // Type into an input await page.type('#email', '[email protected]'); // Select from a dropdown await page.select('#country', 'US'); // Check a checkbox await page.click('input[type="checkbox"]'); // Get text content const heading = await page.$eval('h1', el => el.textContent); console.log(heading);

For more complex interactions, grab an ElementHandle:

javascript
const button = await page.$('[data-testid="checkout"]'); await button.click(); // Get multiple elements const items = await page.$$('.product-card'); console.log(`Found ${items.length} products`);

Waiting for Things

Puppeteer provides explicit wait methods that handle most timing issues:

javascript
// Wait for navigation to complete await page.goto('https://example.com', { waitUntil: 'networkidle0' }); // Wait for a selector to appear await page.waitForSelector('.results-loaded'); // Wait for a function to return true await page.waitForFunction(() => { return document.querySelectorAll('.item').length > 10; }); // Wait for network request to finish await page.waitForResponse(response => response.url().includes('/api/data') && response.status() === 200 );

The waitUntil options for navigation:

  1. load: Wait for the load event (default)
  2. domcontentloaded: Wait for DOMContentLoaded
  3. networkidle0: Wait until no network connections for 500ms
  4. networkidle2: Wait until ≤2 network connections for 500ms

Use networkidle0 for SPAs that load data after initial render.

Network Interception

One of Puppeteer's most powerful features is request interception. You can modify, block, or mock any network request:

javascript
await page.setRequestInterception(true); page.on('request', request => { // Block images and stylesheets for faster loading if (['image', 'stylesheet', 'font'].includes(request.resourceType())) { request.abort(); } else { request.continue(); } }); await page.goto('https://example.com');

Mock API responses for testing:

javascript
await page.setRequestInterception(true); page.on('request', request => { if (request.url().includes('/api/user')) { request.respond({ status: 200, contentType: 'application/json', body: JSON.stringify({ id: 1, name: 'Test User' }) }); } else { request.continue(); } });

Screenshots and PDFs

Puppeteer excels at generating visual output:

javascript
// Full page screenshot await page.screenshot({ path: 'fullpage.png', fullPage: true }); // Specific element only const element = await page.$('.hero-section'); await element.screenshot({ path: 'hero.png' }); // PDF generation await page.pdf({ path: 'page.pdf', format: 'A4', printBackground: true, margin: { top: '1cm', bottom: '1cm' } });

For high-DPI screenshots:

javascript
await page.setViewport({ width: 1280, height: 800, deviceScaleFactor: 2 // 2x resolution });

Running in CI Environments

Headless Chrome needs some specific flags in containerized environments:

javascript
const browser = await puppeteer.launch({ headless: true, args: [ '--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-gpu' ] });

A minimal Dockerfile:

dockerfile
FROM node:20-slim RUN apt-get update && apt-get install -y \ chromium \ --no-install-recommends && \ rm -rf /var/lib/apt/lists/* ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . CMD ["node", "script.js"]

Testing With Puppeteer

While Puppeteer isn't a test framework, it pairs well with Jest:

javascript
const puppeteer = require('puppeteer'); describe('Homepage', () => { let browser; let page; beforeAll(async () => { browser = await puppeteer.launch(); }); beforeEach(async () => { page = await browser.newPage(); }); afterEach(async () => { await page.close(); }); afterAll(async () => { await browser.close(); }); test('displays correct title', async () => { await page.goto('https://example.com'); const title = await page.title(); expect(title).toContain('Example'); }); test('navigation works', async () => { await page.goto('https://example.com'); await page.click('a'); await page.waitForNavigation(); expect(page.url()).toContain('iana.org'); }); });

When to Choose Puppeteer

Puppeteer fits specific use cases well:

Use CasePuppeteer Fit
Chrome-only testingExcellent
Web scrapingExcellent
PDF generationExcellent
Screenshot automationExcellent
Cross-browser testingPoor, use Playwright or Selenium
Non-JavaScript teamsPoor, Node.js only

If you're building a scraper, generating PDFs, or only care about Chrome, Puppeteer is lightweight and fast. For cross-browser testing or teams using Python/Java, consider alternatives.

Skip the complexity with a screenshot API

Puppeteer is powerful, but running headless browsers requires infrastructure: servers with enough memory, Chrome dependencies, and handling edge cases like timeouts, crashes, and zombie processes. For screenshot-specific use cases, a dedicated API can be simpler.

AllScreenshots handles the browser complexity for you:

bash
curl -X POST 'https://api.allscreenshots.com/v1/screenshots' \ -H 'X-API-Key: your-api-key' \ -H 'Content-Type: application/json' \ -d '{"url": "https://example.com", "fullPage": true}'

No browser management, no Dockerfile configuration, no memory tuning. The API handles full-page captures, device emulation, ad blocking, and dynamic content rendering. You get consistent results without maintaining Puppeteer infrastructure.

For testing and complex automation where you need network interception or custom browser behavior, Puppeteer remains the right choice. For screenshot capture at scale, try AllScreenshots free.

Conclusion

Puppeteer offers a direct, low-overhead way to automate Chrome and Firefox from Node.js. Its tight integration with browser automation protocols enables features such as network interception, performance tracing, and PDF generation that higher-level tools may abstract away.

Start with simple navigation and screenshots. Add network interception when you need to mock APIs or speed up tests. The API is intuitive enough that most developers are productive within an hour.

Just remember the scope: Puppeteer is a browser automation library, not a comprehensive testing framework. Pair it with Jest or Mocha for assertions, and use Playwright or Selenium when your main requirement is broad cross-browser test orchestration.

Find out how easy it is to capture and share pixel-perfect screenshots at scale using Allscreenshots. Sign up for a free account and start integrating your first screenshot API call today.

Start with one request

Free plan: 100 screenshots. No credit card.

Get an API key
  • Full-page captures
  • Popups and repeated sticky bars removed
  • Markdown, JSON and PDF output
  • Crawl a site from one URL
  • Desktop, tablet and phone in one image
  • Works in n8n, Make and Zapier
  • MCP server for AI assistants