javascript - 如何在 page.evaluate() 的函数参数中将 page 作为参数传递?
问题描述
当我将页面作为参数传递时出现此错误:
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'BrowserContext'
| property '_browser' -> object with constructor 'Browser'
--- property '_defaultContext' closes the circle Are you passing a nested JSHandle?
at JSON.stringify (<anonymous>)
我对应的代码是:
const result = await page.evaluate = ( async (page, selector1, selector2) => {
let result = [];
const sel = document.querySelectorAll(selector1);
if(sel.length) {
const total = sel.length;
for(let i=0;i<total;i++) {
result.push(document.querySelector(selector1 + ` div:nth-child(${i+1}) span a`).textContent);
await page.click(selector2 + ` div:nth-child(${i+1})`);
}
}
return result;
}, page, selector1, selector2);
如何包含 page 参数?
解决方案
我不确定您是否了解该.evaluate
方法的工作原理。此方法在浏览器上下文中执行代码,因此要单击一个元素,您可以使用这样的代码,就好像您在浏览器中编写它一样。您不能page
在浏览器和Node.js
. 我在方法中更改了您的代码.evaluate
,它应该如下所示:
const result = await page.evaluate((selector1, selector2) => {
const result = [];
const sel = document.querySelectorAll(selector1);
if (sel.length) {
const total = sel.length;
for (let i = 0; i<total; i++) {
result.push(sel.querySelector(`div:nth-child(${i+1})`).textContent);
document.querySelector(`${selector2} div:nth-child(${i+1})`).click();
}
}
return result;
}, selector1, selector2);
推荐阅读
- java - 变为可见时无法点击Android按钮
- mongodb - 将位置与两个查询数组一起使用,其中一个不需要影响位置运算符
- ios - 尽管核心数据“已成功保存!”,但表视图仍为空白
- python - 在 django 中上传大文件的问题
- django - 从外部 API 检索数据并在 django admin 中显示
- javascript - 使用表格 ID 删除动态 HTML 表格?
- spring-boot - 将多个存储库添加到 Spring 云配置服务器
- python - Python等待'外部函数Discord.py
- java - 根据给定输入值列表对对象列表进行排序
- mysql - 如何在 Vue 和 Laravel 中使用 axios 上传图像文件和数据对象?