在 puppeteer 中使用 CSS 选择器单击元素

Click element using CSS selector in puppeteer

我想在 puppeteer 上使用 css 选择器单击一个对象,我正在使用设备模拟器 (iphone X)。

对于同一对象,我有以下两个 css 选择器,

div:nth-of-type(1) > .canvasContentDiv.container_1vt1y2p > div > div:nth-of-type(4) .react-knockout-control > div

[aria-labelledby='pa-gallery-label-1'] [data-control-id='24'] [touch-action]

任何帮助如何做到这一点,试过以下两种方法但不起作用?

方法一:

const elementHandle = await page.evaluate(() => { const element = document.querySelector("[aria-labelledby='pa-gallery-label-1'] [data-control-id='24'] [touch-action]"); });
await page.waitFor(500);
elementHandle.click();

方法二:

 await page.click("[aria-labelledby='pa-gallery-label-1'] [data-control-id='24'] [touch-action]");

尝试通过这种方式获取句柄,以检测您的查询在 运行 时间是否正常工作:

const query = "[aria-labelledby='pa-gallery-label-1'] [data-control-id='24'] [touch-action]";
const element = await this.page.$(query);
if (element) {
  await element.click();
  console.log('element clicked');
}
else {
  console.log('element not found');
}

如果找到并单击该元素,那么我会建议您 运行 可见模式下的浏览器 {headless: false}、运行 附带调试器的 VS Code 中的代码,以及点击后暂停执行。这将允许您在它启动的 Chromium 实例中打开 DevTools,您可以检查控制台中发生的事情。