我有多个.home元素,我想单击最后一个
以下是我所写的:
await page.waitForSelector('.home');
const el = await page.$eval('.home', (elements) => elements[elements.length - 1]);
el.click();但不起作用。相反,我得到了以下错误:
TypeError: Cannot read property 'click' of undefined
at open_tab (C:\wamp64\www\home_robot\robot.js:43:12)
at process._tickCallback (internal/process/next_tick.js:68:发布于 2019-05-18 15:10:12
最简单的方法是使用page.$$获取.home元素的所有元素句柄,然后单击数组中的最后一个元素:
const elements = await page.$$('.home');
await elements[elements.length - 1].click();为什么您的代码不能工作
您不能使用page.$eval返回元素句柄,因为您返回的数据在从浏览器发送到Node.js环境时将通过JSON.stringify序列化。
引用上述链接的文档:
返回:承诺[Serializable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description)承诺,它解析为
pageFunction的返回值
由于DOM元素不能序列化,所以不能在Node.js脚本中单击它,而是得到错误。您必须使用page.$或page.$$来获取元素句柄。
https://stackoverflow.com/questions/56200057
复制相似问题