/

How to Click a Link with Specific Text Using Puppeteer

How to Click a Link with Specific Text Using Puppeteer

In this tutorial, we will explore how to click a link with specific text using Puppeteer, a powerful Node.js library for controlling headless Chrome or Chromium.

When working with web automation, it is often necessary to interact with buttons or links on a page. In this specific case, let’s say we want to click an “Accept all” cookie button.

To accomplish this task, we can use the following code snippet:

1
2
3
4
const [linkCookie] = await page.$x("//a[contains(., 'Accept all')]");
if (linkCookie) {
await linkCookie.click();
}

Here, we utilize the page.$x() function, which allows us to evaluate XPath expressions within the context of the current page. The XPath expression "//a[contains(., 'Accept all')]" selects an a element that contains the text “Accept all”. The [linkCookie] assignment utilizes array destructuring to extract the first element from the resulting array.

If the linkCookie element exists (i.e., if a match is found), we invoke the click() method to simulate a user click on the element.

Note: If the button is an HTML button element instead of an a element, the code snippet needs to be adjusted accordingly:

1
page.$x("//button[contains(., 'Accept all')]");

Make sure to select the appropriate element type in your XPath expression.

For a more comprehensive guide on Puppeteer, be sure to check out my full Puppeteer tutorial. It covers various topics, including navigating pages, interacting with forms, taking screenshots, and more.

tags: [“Puppeteer”, “web automation”, “web scraping”, “JavaScript”]