为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

心有法竹 2022-06-05 16:56:23
当我使用page.evaluate并将变量传递给它时,它们是未定义的。let reaction;// First console.log actually logs the string as expectedconsole.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)我在代码中添加了一些注释以显示未定义反应标题的位置。
查看完整描述

1 回答

?
牧羊人nacy

TA贡献1862条经验 获得超7个赞

从(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.


查看完整回答
反对 回复 2022-06-05
  • 1 回答
  • 0 关注
  • 302 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号