Learn the basics of Puppeteer installation, setup, and your first automation script
First, let's install Puppeteer in your project. Make sure you have Node.js installed on your system.
# Install Puppeteer
npm install puppeteer
# Or using yarn
yarn add puppeteer
Puppeteer will download a recent version of Chromium (~170MB) that's guaranteed to work with the API.
Let's create a simple script that opens a webpage and takes a screenshot.
const puppeteer = require('puppeteer');
(async () => {
// Launch a new browser instance
const browser = await puppeteer.launch();
// Create a new page
const page = await browser.newPage();
// Navigate to a website
await page.goto('https://example.com');
// Take a screenshot
await page.screenshot({ path: 'example.png' });
// Close the browser
await browser.close();
})();
Learn essential Puppeteer operations for web automation.
// Go to a page
await page.goto('https://example.com');
// Go back
await page.goBack();
// Go forward
await page.goForward();
// Reload page
await page.reload();
// Click an element
await page.click('#button-id');
// Type text
await page.type('#input-id', 'Hello World');
// Select dropdown option
await page.select('select#colors', 'blue');
// Get text content
const text = await page.$eval('#element', el => el.textContent);
// Get attribute
const href = await page.$eval('a', el => el.href);
// Get multiple elements
const links = await page.$$eval('a', links =>
links.map(link => link.href)
);
// Wait for element
await page.waitForSelector('#dynamic-content');
// Wait for navigation
await page.waitForNavigation();
// Wait for timeout
await page.waitForTimeout(1000);
Follow these best practices for robust Puppeteer automation.
Use try-catch blocks to ensure browser cleanup even if errors occur.
const browser = await puppeteer.launch();
try {
const page = await browser.newPage();
// Your automation code here
} finally {
await browser.close();
}
Configure timeouts for page loads and element waits.
// Set default timeout
page.setDefaultTimeout(30000);
// Set navigation timeout
page.setDefaultNavigationTimeout(60000);
Define consistent viewport dimensions for predictable results.
await page.setViewport({
width: 1280,
height: 720,
deviceScaleFactor: 1
});