迭代页面中的链接并根据条件单击
Iterate over links in a page and click based on condition
我正在抓取一个网页,我只需要下载该网页上满足特定条件的文件。我怎样才能在 puppeteer 中实现这一点?
我可以使用选择器定位元素并使用 page.$$eval
获取我需要的属性,但我不知道如何单击 link。
const sectionLinks = await page.$$eval('#mainsection a', aTags => aTags.map(a => a.innerText));
for (const sectionLink of sectionLinks) {
if (sectionLink.toUpperCase() == 'THEONEIWANT') {
console.log('download');
//this is where I want to click the link
}
}
您没有获取元素句柄。您只返回它们的 innerText
值。
你可以做的是,首先获取所有元素,然后像这样遍历它们:
const elements = await page.$$('#mainsection a');
for (const el of elements) {
const innerText = await page.evaluate(el => el.innerText, el);
if (innerText.toUpperCase() == 'THEONEIWANT') {
await el.click();
}
}
这将一一遍历所有元素,读取它们的 innerText
值,检查条件是否匹配,然后单击它。
优化
如果有很多链接,这可能需要一些时间。您可以通过使用基于您要查找的文本匹配的选择器(查看 了解更多信息)或使用如下表达式来检查条件是否在客户端匹配来改进此代码。这将立即检查所有元素:
const shouldElementBeClicked = page.evaluate((...args) => args.map(el => el.innerText === '...'), ...elements);
这将生成一个带有布尔值的数组,表示 elements
数组中相同位置的元素是否满足条件。
我正在抓取一个网页,我只需要下载该网页上满足特定条件的文件。我怎样才能在 puppeteer 中实现这一点?
我可以使用选择器定位元素并使用 page.$$eval
获取我需要的属性,但我不知道如何单击 link。
const sectionLinks = await page.$$eval('#mainsection a', aTags => aTags.map(a => a.innerText));
for (const sectionLink of sectionLinks) {
if (sectionLink.toUpperCase() == 'THEONEIWANT') {
console.log('download');
//this is where I want to click the link
}
}
您没有获取元素句柄。您只返回它们的 innerText
值。
你可以做的是,首先获取所有元素,然后像这样遍历它们:
const elements = await page.$$('#mainsection a');
for (const el of elements) {
const innerText = await page.evaluate(el => el.innerText, el);
if (innerText.toUpperCase() == 'THEONEIWANT') {
await el.click();
}
}
这将一一遍历所有元素,读取它们的 innerText
值,检查条件是否匹配,然后单击它。
优化
如果有很多链接,这可能需要一些时间。您可以通过使用基于您要查找的文本匹配的选择器(查看
const shouldElementBeClicked = page.evaluate((...args) => args.map(el => el.innerText === '...'), ...elements);
这将生成一个带有布尔值的数组,表示 elements
数组中相同位置的元素是否满足条件。