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

标签 node.js css-selectors puppeteer chromium

我尝试单击网页上的 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();

最佳答案

问题是你有三个 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;
  }
}

关于node.js - Puppeteer 无法识别仅具有类型和类的选择器,但接受完整的选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59843251/

相关文章:

node.js - ubuntu 14.04 上的 ssl 证书问题

css - 是否有 "previous sibling"选择器?

html - 是否有用于 :nth-of-type(n+2):nth-of-type(-n+4)? 析取的 CSS 选择器

javascript - 如何在 puppeteer 中加载脚本?

javascript - 如何在puppeteer page.evaluate中使用url模块

javascript - 了解存储在 Firebase 云功能中的 Firebase 存储中的视频持续时间的最简单方法是什么?

javascript - 如何实现网站的cookies scraper?

node.js - 如何在ftp服务器上运行node.js脚本?

Contact-Form 7 插件的 CSS,在整个网站上没有被平等地选择

javascript - 在 Pyppeteer (Python Puppeteer) 中通过文本选择按钮