Using Puppeteer in Javascript to locate text on a webpage

I am currently exploring ways to utilize Puppeteer for searching an HTML page for a specific product name.

Just to give you an idea, the HTML code looks something like this:

<a class="example" href = "example_link">PRODUCT NAME</a>

My goal with Puppeteer is to locate the PRODUCT NAME either through relevant keywords or the exact name itself, and then instruct it to click on the text which will in turn redirect the browser to the corresponding href link.

Your assistance with this matter would be highly appreciated!

Thank you so much.

Answer №1

It seems like you are looking to locate a link based on its text content for clicking purposes. Here are a couple of approaches you can take:

const puppeteer = require('puppeteer');

(async function main() {
  try {
    const browser = await puppeteer.launch({ headless: false, defaultViewport: null });
    const [page] = await browser.pages();

    const textToFind = 'More information...';

    // Method 1.

    await page.goto('https://example.org/');

    const link1 = await page.evaluateHandle(
      text => [...document.querySelectorAll('a')].find(a => a.innerText === text),
      textToFind
    );
    await link1.click();
    await page.waitFor(3000);

    // Method 2.

    await page.goto('https://example.org/');

    const [link2] = await page.$x(`//a[text()="${textToFind}"]`);
    await link2.click();
    await page.waitFor(3000);

    await browser.close();
  } catch (err) {
    console.error(err);
  }
})();

If you need to find a partial match, consider using includes() in place of === for the first method and utilize the XPath contains() function for the second method.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Videogular: hh:mm:ss Date filter not functioning properly

I am currently working on integrating Videogular into my audio player application. Below are the settings provided in the example code on this particular page: <vg-time-display>{{ currentTime | date:'mm:ss' }}</vg-time-display> ...

Is there a way to automate clicking a button when an ajax request is successful through programming?

I am currently working on implementing an ajax cart feature for an e-commerce website. The specific functionality I am aiming to achieve is that when a user clicks the 'add to cart' button, the item is added to the cart and then the user is autom ...

What is the best way to locate and send a message to a particular channel within a server?

I've been working on a Discord bot using Discord.js and I'm currently attempting to create a welcome command. My goal is to send a message to a specific channel within my server. However, due to recent updates in discord.js, I'm having troub ...

Attempting to access a shared php/javascript library using mod_rewrite

Let's dive into a fresh perspective on a question I previously raised: I've crafted a mod_rewrite snippet that checks for the existence of JavaScript, CSS, and PHP files on the subdomain they are called from (e.g., subdomain.example.com). If the ...

Handling versioning when a property is deprecated in semver

We've implemented semver for maintaining our CSS libraries, ensuring we adhere to the official guidelines for versioning. However, when we render a class obsolete (or for JavaScript - a property or argument), what is the recommended action? The clien ...

AngularJS - directive template is not being compiled correctly

I am facing an issue with AngularJS. .directive('field', ['$routeParams', function($routeParams){ return { restrict: 'E', compile: function(tElement, tAttributes) { var template ...

Preserve and recover the dynamic form value following an AJAX update

Looking for a solution for saving and restoring user comments on dynamically created form fields in a page where users can comment on posts. How can we save and restore the typed comments before an ajax refreshes the div holding all the post and comments? ...

Is it possible to achieve seamless image transitions in Firefox like it does in Chrome?

To achieve the desired effect, you may need to use some javascript. Visit aditagarwal.com for more information. Styling with CSS: .images-wrapper{ position: fixed; left: 0; top: 80px; bottom: 0; width: 100%; height: 100vh; an ...

Implementing conditional logic using v-if and v-else statements

I am currently diving into the world of vue.js! I have enrolled in a course on Udemy to expand my knowledge. While experimenting with basic conditional statements, specifically if-else statements, I encountered an issue. Despite following the instruction ...

What could be causing the issue of req.body being undefined within the destination function of Multer's diskStorage?

I'm currently utilizing Multer for managing file uploads within my Express.js application. However, I've encountered an issue when attempting to access the req.body values in the destination function of Multer's diskStorage option – it con ...

typescript: define the type of an object that behaves like a map

My current approach involves utilizing an object to store a map, where keys are strings and values are of a fixed type T. Upon looking up a key in the object, the type inference automatically assigns it the type T. However, there is a possibility that it ...

Hide <a> by setting its display property to none

Below is the HTML code: <td> <a class="link" href="#"> <span class="download">Link</span> </a> <a class="link" href="#"> <span class="csvdownload">Link 2</span> </a> </td> I am lo ...

Performing an Angular JS $http post request with URL parameters included in the GET request

I am running into an issue when trying to post data with GET parameters to a URL using Angular's $http method. Here is the URL I am trying to post to: http://localhost/api/?r=page/product However, my attempts at posting data to this URL using AJAX h ...

Calculating the sum of table columns with the help of knockout.js

Is there a way to calculate the table columns using knockout.js? I am familiar with jQuery but new to knockout.js and unsure how to approach this. Instead of generating the table data using JSON, I would like to directly create it in the HTML table itself. ...

Problem encountered when utilizing map() function - it returns undefined

const items = [ { item: "apple", cost: 2 }, { item: "orange", cost: 4 }, { item: "carrot", cost: "" }, { item: "grapes", cost: 5 }, { item: "milk", cost: 3 }, { item: "bread" ...

Occasionally I encounter the message: "Error: Server unexpectedly terminated with status 1."

I created an automated test to check the login page, with testing data stored in a JSON file. Here is the code in index.js: const fs = require("fs"); fs.writeFileSync("testReport.json", "{}", "utf-8"); const { login } = require("./tests/login"); const au ...

Incorporating DefinitelyTyped files into an Angular 2 project: A step-by-step guide

I am currently developing an application using angular 2 and node.js. My current task involves installing typings for the project. In the past, when starting the server and activating the TypeScript compiler, I would encounter a log with various errors rel ...

Activate Bootstrap - navigate to a specific tab and scroll to a designated anchor upon link click

My goal is to switch to another tab and scroll to a specific part of the page after clicking on a link inside a tab. Unfortunately, although I have successfully switched tabs, I am unable to scroll down to the anchor point. I would greatly appreciate any ...

Express server is receiving undefined post parameters from Axios in Vue, even though they are clearly defined in Vue

Within my code, I am utilizing an <img> element as shown below: <img v-bind:word = "thing" @click="action" align="center" src="../assets/pic.png"/> Alongside, there is a method structured in this manner: ...

Designing a login system with MEAN stack architecture?

I am currently in the process of building a web application using the MEAN stack (MongoDB, Express, AngularJS, and node.js). Specifically, I am working on implementing a login system and securing certain routes in my Angular app so that they are only acces ...