Tutorial
Introduction to Puppeteer for Browser Automation

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:
- Headless by default: Runs without a visible UI, perfect for CI
- Full page interaction: Click, type, scroll, drag-and-drop
- Network interception: Mock API responses, block resources
- Performance tracing: Capture Chrome DevTools timeline data
- PDF and screenshot generation: Built-in, high-quality output
Getting Started
Install Puppeteer in any Node.js project:
npm install puppeteerHere's a minimal script that navigates to a page and takes a screenshot:
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:
| Object | Purpose |
|---|---|
Browser | A browser instance (Chromium or Firefox) |
BrowserContext | An isolated session, like an incognito window |
Page | A single tab, where most interaction happens |
Frame | An iframe within a page |
ElementHandle | A 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.
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:
// 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:
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:
// 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:
load: Wait for theloadevent (default)domcontentloaded: Wait forDOMContentLoadednetworkidle0: Wait until no network connections for 500msnetworkidle2: 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:
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:
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:
// 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:
await page.setViewport({
width: 1280,
height: 800,
deviceScaleFactor: 2 // 2x resolution
});Running in CI Environments
Headless Chrome needs some specific flags in containerized environments:
const browser = await puppeteer.launch({
headless: true,
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-gpu'
]
});A minimal 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:
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 Case | Puppeteer Fit |
|---|---|
| Chrome-only testing | Excellent |
| Web scraping | Excellent |
| PDF generation | Excellent |
| Screenshot automation | Excellent |
| Cross-browser testing | Poor, use Playwright or Selenium |
| Non-JavaScript teams | Poor, 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:
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.
Related Resources
- What is Puppeteer and How Does It Work? — a deeper conceptual guide to Puppeteer's architecture
- Introduction to Playwright for End-to-End Testing — how Playwright compares for cross-browser testing
- Screenshot Automation — automate captures without managing browser infrastructure
- Visual Regression Testing — use screenshots to catch UI bugs automatically
- Screenshot API Performance Tips — optimizing screenshot capture at scale
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.


