basic examples in puppeteer
Puppeteer is a Node.js library that provides a high-level API to control and interact with Chromium-based browsers programmatically. Here’s a step-by-step overview of how Puppeteer works:
1. Installation
First, you need to install Puppeteer as a dependency in your Node.js project using npm or yarn:
npm install puppeteer
2. Launching a Browser Instance
Puppeteer allows you to launch a new instance of a Chromium-based browser. Here's how you typically launch a browser:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
// Further actions like opening pages, navigating, etc.
})();
puppeteer.launch()
: This function launches a new browser instance with default settings. You can pass various options to configure the browser, such asheadless
mode (running without a visible UI),executablePath
(to specify the path to the browser executable), and more.
3. Opening a New Page
Once you have a browser instance, you can open new pages (tabs) within that browser:
const page = await browser.newPage();
browser.newPage()
: Creates a new tab in the browser instance. You can interact with this page object to navigate to URLs, interact with elements on the page, evaluate JavaScript, take screenshots, and more.
4. Interacting with the Page
You can automate interactions with the opened page using Puppeteer’s API methods. Here are some common actions:
-
Navigation:
await page.goto('https://example.com');
-
Clicking Elements:
await page.click('button#submit');
-
Typing Text:
await page.type('input#username', 'JohnDoe');
-
Taking Screenshots:
await page.screenshot({ path: 'screenshot.png' });
-
Evaluating JavaScript:
const pageTitle = await page.evaluate(() => document.title); console.log('Page title:', pageTitle);
5. Closing the Browser Instance
After you've finished your automation tasks, it's good practice to close the browser instance:
await browser.close();