传递给 page.evaluate 的变量未定义

当我使用page.evaluate并将变量传递给它时,它们是未定义的。


let reaction;

// First console.log actually logs the string as expected

console.log(reactionTitle);

await this.page.evaluate(function (reactionTitle, reaction) {

    // Second console.log logs undefined in the website's console

    console.log(reactionTitle);

    document.querySelectorAll('span.embedAuthorName-3mnTWj').forEach(s => {

        // Third console.log logs all innerTexts in the website's console

        console.log(s.innerText)

        if (s.innerText == reactionTitle) {

            console.log(s);

            reaction = s.offsetParent.offsetParent.querySelector('.container-1ov-mD').querySelector('.reactions-12N0jA').querySelector('div').querySelector('.reaction-1hd86g').querySelector('.reactionInner-15NvIl');

            console.log(reaction)

        }

    });

}, (reactionTitle, reaction));


console.log(reaction)

我在代码中添加了一些注释以显示未定义反应标题的位置。


心有法竹
浏览 303回答 1
1回答

牧羊人nacy

从(reactionTitle, reaction)in 参数中删除括号:await this.page.evaluate((reactionTitle, reaction) => { ... }, reactionTitle, reaction)或者await this.page.evaluate(({reactionTitle, reaction}) => { ... }, {reactionTitle, reaction})page.evaluate在页面上下文中执行,并且与 puppeteer 执行环境分开。我建议看一下文档和架构。要从 puppeteer 中的页面内上下文访问变量,您需要返回变量。请注意,变量必须是可序列化的:const result = await this.page.evaluate(({reactionTitle, reaction}) => {     ...     return reaction;}, {reactionTitle, reaction});如果返回值是页内对象,请使用evaluateHandle.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript