puppeteer nodejs,不能取评估范围之外的值

问题描述 投票:0回答:1

我有一个 puppeteer 程序,我获取 div 的元素,然后处理它的子元素。 当我尝试使用

console.log()
登录时,我可以检查并查看浏览器上的值。然而在 Node js、控制台上,我看不到应该推送到数组的值。

这是一个较长的程序,但我只是发布与我的问题相关的函数的代码。这是什么原因呢?我还检查了如何将变量传递到评估函数?以与外部范围变量进行交互

.evaluate()
.. 如果
console.log()
给出了正确的值,则表示获得了该值,但
push
方法失败。我在浏览器或程序日志上没有看到警告或错误。原因是什么?

async function observer(){
    await page.waitForFunction("document.querySelectorAll(\"div[id='myid']\").length > 1")
    var arrayOfMailNames = []
    await page.evaluate((arrayOfMailNames) => {
        var parentDiv = document.querySelectorAll("div[id='myid']");
        for(var t = 0; t < parentDiv.length; t++){
                if(parentDiv[t].getAttribute('id') !=null){
                    console.log(` ${parentDiv[t].split(";")[0]}`); //returns correct values on the browser's console. 
                    arrayOfMailNames.push(parentDiv[t].split(";")[0]); //apparently doesnt work
                }
        }
    }, arrayOfMailNames)
    console.log(`${arrayOfMailNames.length}`); //logs 0 on nodejs terminal.. which is not correct because I used push above
}
javascript node.js puppeteer
1个回答
0
投票

您应该从评估回调中

return
,该回调在页面上下文中运行。然后将其返回值分配给您需要的变量。

var arrayOfMailNames = [];
arrayOfMailNames = await page.evaluate(() => {
    var parentDiv = document.querySelectorAll("div[id='myid']");
    var tempArray = [];
    for (var t = 0; t < parentDiv.length; t++) {
        if (parentDiv[t].getAttribute('id') != null) {
            console.log(` ${parentDiv[t].textContent.split(";")[0]}`); 
            tempArray.push(parentDiv[t].textContent.split(";")[0]);
        }
    }
    return tempArray;
});
© www.soinside.com 2019 - 2024. All rights reserved.