Back to Homepage
Thursday 22 August 2024
130

Puppeteer: How to Click Button

Puppeteer is a powerful Node.js library that enables developers to control a headless version of Chrome or Chromium via the DevTools Protocol. One of the most common tasks in web automation is clicking buttons. Whether it's submitting a form, navigating to another page, or triggering an event, clicking a button with Puppeteer is straightforward.

Step-by-Step Explanation

1. Install and Set Up Puppeteer:

  • Start by installing Puppeteer via npm:
npm install puppeteer
  • Import Puppeteer in your Node.js script:
const puppeteer = require('puppeteer');

2. Launch Browser and Open a New Page:

const browser = await puppeteer.launch();
   const page = await browser.newPage();

3. Navigate to the Desired Webpage:

  • Use the goto method to navigate to the webpage where the button is located.
await page.goto('https://example.com');

4. Select and Click the Button:

  • Identify the button using a selector (e.g., id, class, or text) and click it using the click method.
await page.click('button#submitButton'); // Example using an ID selector

5. Wait for the Action to Complete:

  • Often, a button click triggers a navigation or an action. Use waitForNavigation or other waiting methods to ensure that Puppeteer waits for the action to complete.
await page.waitForNavigation();

6. Close the Browser:

  • After completing the action, close the browser.
await browser.close();

Examples of Clicking Buttons with Puppeteer

Clicking a Button by ID

await page.goto('https://example.com');
await page.click('button#loginButton'); // Clicks a button with the ID 'loginButton'

Clicking a Button by Class

If the button has a class, you can target it like this:

await page.goto('https://example.com');
await page.click('button.btn-primary'); // Clicks a button with the class 'btn-primary'

Clicking a Button Containing Specific Text

You can also select a button based on its text content using XPath:

const button = await page.$x("//button[contains(text(), 'Submit')]");
await button[0].click();

Handling Buttons Inside iFrames

If the button is inside an iframe, you'll need to access the iframe first:

const frame = await page.frames().find(frame => frame.name() === 'iframeName');
await frame.click('button#submitButton');

References

This guide provides a simple yet effective overview of how to automate button clicks using Puppeteer. For more advanced use cases, refer to the official Puppeteer documentation.

Share:
Created by:
Author photo

Jorge García

Fullstack developer