【问题标题】:How to pass page as an argument in the function parameter of page.evaluate()?如何在 page.evaluate() 的函数参数中将 page 作为参数传递?
【发布时间】:2020-10-23 09:00:39
【问题描述】:

当我将页面作为参数传递时出现此错误:

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);

如何包含页面参数?

【问题讨论】:

    标签: javascript html node.js dom-events puppeteer


    【解决方案1】:

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

    【讨论】:

    • 哦,不错。现在我知道 .evaluate 是如何工作的。感谢您的帮助。
    猜你喜欢
    • 2018-03-20
    • 2021-01-14
    • 2021-04-13
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    相关资源
    最近更新 更多