问题
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>
回答1:
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)
回答2:
If I got you right, the following piece of code should let you click on that link:
const puppeteer = require('puppeteer');
(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("a[href$='a05ivugj2']");
await browser.close();
})();
回答3:
The following function will click the first element that matches certain text:
const clickText = text => {
return page.evaluate(text => [...document.querySelectorAll('*')].find(e => e.textContent.trim() === text).click(), text);
};
You can use the function in your Puppeteer script using the following method:
await clickText('Supreme®/The North Face® Leather Shoulder Bag');
来源:https://stackoverflow.com/questions/52904802/how-to-click-a-button-on-a-website-using-puppeteer-without-any-class-id-as