puppeteer querySelector 不是有效的选择器

puppeteer querySelector is not a valid selector

我有一个代码如下:

page.click('div.button-table div:contains(Who) div.square-button:nth-child(1)')

当 puppeteer 运行 这段代码时,它会引发错误:

简介

Failed to execute 'querySelector' on 'Document': 'div.button-table div:contains(Who) div.square-button:nth-child(1)' is not a valid selector.

已满

 Error: Evaluation failed: DOMException: Failed to execute 'querySelector' on 'Document': 'div.button-table div:contains(Who) div.square-button:nth-child(1)' is not a valid selector.
at __puppeteer_evaluation_script__:1:33
  at ExecutionContext.evaluateHandle (node_modules/puppeteer/lib/ExecutionContext.js:124:13)
  at <anonymous>
-- ASYNC --
  at ExecutionContext.<anonymous> (node_modules/puppeteer/lib/helper.js:144:27)
  at ElementHandle.$ (node_modules/puppeteer/lib/ExecutionContext.js:529:50)
  at ElementHandle.<anonymous> (node_modules/puppeteer/lib/helper.js:145:23)
  at Frame.$ (node_modules/puppeteer/lib/FrameManager.js:456:34)
  at <anonymous>
-- ASYNC --
  at Frame.<anonymous> (node_modules/puppeteer/lib/helper.js:144:27)
  at Frame.click (node_modules/puppeteer/lib/FrameManager.js:735:31)
  at Frame.<anonymous> (node_modules/puppeteer/lib/helper.js:145:23)
  at Page.click (node_modules/puppeteer/lib/Page.js:973:29)
  at Proxy.fillInAudience (libs/page/brand_create_quote_page.js:67:21)
  at Proxy.<anonymous> (libs/logger.js:38:27)
  at Context.it (ui/brand/create_quote_spec.js:53:16)
  at <anonymous>

但是这个选择器可以 运行 在 Devtools 中成功 - $('div.button-table div:contains(Who) div.square-button:nth-child(1)').text()

我还弄清楚如果我删除 div:contains(Who),puppeteer 可以 运行 它而不会惊慌。

有什么想法吗?

谢谢!

Puppeteer 使用的 document.querySelector internally. So you would be able to use any CSS Selector. The problem here is that contains 不是 CSS 选择器,而是 JQuery 功能。

好处是您可以使用 Chrome 开发人员工具测试您的选择器并使用 document.querySelector.

测试它们