Puppeteer无法识别仅具有类型和类的选择器,但会接受完整的选择器

问题描述 投票:0回答:1

我正在尝试单击网页上的cookiewall,但Puppeteer拒绝仅使用类型和类选择器(button.button-action)识别短选择器。将其更改为完整的CSS选择器可解决此问题,但不是可行的解决方案,因为父元素中的任何机会都可能破坏选择器。据我所知这应该不是问题,因为在有问题的页面上,使用document.querySelector("button.button-action")还会返回我尝试单击的元素。

无效的代码:

const puppeteer = require('puppeteer');

const main = async () => {
    const browser = await puppeteer.launch({headless: false,});
    const page = await browser.newPage();
    await page.goto("https://www.euclaim.nl/check-uw-vlucht#/problem", { waitUntil: 'networkidle2' });
    const cookiewall = await page.waitForSelector("button.button-action", {visible: true});
    await cookiewall.click();
};

main();

有效的代码:

const puppeteer = require('puppeteer');

const main = async () => {
    const browser = await puppeteer.launch({headless: false,});
    const page = await browser.newPage();
    await page.goto("https://www.euclaim.nl/check-uw-vlucht#/problem", { waitUntil: 'networkidle2' });
    const cookiewall = await page.waitForSelector("#InfoPopupContainer > div.ipBody > div > div > div.row.actionButtonContainer.mobileText > button", {visible: true});
    await cookiewall.click();
};

main();
node.js css-selectors puppeteer chromium
1个回答
0
投票

问题是您那里有三个button.button-action。而且第一个匹配项不可见。

enter image description here

您可以做的是waitForSelector,但没有可见的位(因为它将检查第一个按钮)。然后遍历所有项目,检查哪个项目是可单击的。

await page.waitForSelector("button.button-action");
const actions = await page.$$("button.button-action");
for(let action of actions) {
  if(await action.boundingBox()){
    await action.click();
    break;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.