首页 > 解决方案 > 如何在 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 参数?

标签: javascripthtmlnode.jsdom-eventspuppeteer

解决方案


我不确定您是否了解该.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);

推荐阅读