如何在 page.evaluate() 的函数参数中将页面作为参数传递?
How to pass page as an argument in the function parameter of page.evaluate()?
当我将页面作为参数传递时出现此错误:
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);
如何包含页面参数?
我不确定您是否了解 .evaluate
方法的工作原理。此方法在浏览器上下文中执行代码,因此要单击某个元素,您可以像在浏览器中编写代码一样使用此类代码。您不能在浏览器和 Node.js
之间传递像 page
这样的复杂对象。我在 .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);
当我将页面作为参数传递时出现此错误:
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);
如何包含页面参数?
我不确定您是否了解 .evaluate
方法的工作原理。此方法在浏览器上下文中执行代码,因此要单击某个元素,您可以像在浏览器中编写代码一样使用此类代码。您不能在浏览器和 Node.js
之间传递像 page
这样的复杂对象。我在 .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);