Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to click a button on a website using Puppeteer without any class, id ,... assigned to it?

So I want to click on a button on a website. The button has no id, class,... So I should find a way to click the button with the name that's on it. In this example I should click by the name "Supreme®/The North Face® Leather Shoulder Bag"

This is my code in Node.js

const puppeteer = require('puppeteer');

let scrape = async () => {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
await page.goto('https://www.supremenewyork.com/shop/all/bags');
await page.click(...);
browser.close();
return result;
};

This is the element that I want to click:

<a class="name-link" href="/shop/bags/a9cz4te2r/rsth86fbl">Supreme®/The 
North Face® Leather Shoulder Bag</a>
like image 826
wizencrowd Avatar asked Mar 06 '23 05:03

wizencrowd


1 Answers

Here is a way to collect that data. Try these on your browsers console first.

[...document.querySelectorAll('a.name-link')]
.filter(element => 
  element.innerText.includes('Supreme®/The North Face® Leather Shoulder Bag')
)

What's going on here?

  • document.querySelectorAll finds all element with that selector.
  • .filter will return the result that matches the query.
  • .includes will return data that includes a given string.

If a.name-link does not work, then look for a, if that does not work, then find the parent item and use that.

Once you got the element on your browser, you can apply that on your code, click it etc.

Usage:

You can use page.evaluate to filter and click.

const query = "Supreme®/The North Face® Leather Shoulder Bag";

page.evaluate(query => {
  const elements = [...document.querySelectorAll('a.name-link')];

  // Either use .find or .filter, comment one of these
  // find element with find
  const targetElement = elements.find(e => e.innerText.includes(query));

  // OR, find element with filter
  // const targetElement = elements.filter(e => e.innerText.includes(query))[0];

  // make sure the element exists, and only then click it
  targetElement && targetElement.click();
}, query)
like image 118
Md. Abu Taher Avatar answered Mar 10 '23 10:03

Md. Abu Taher