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>
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With