当我使用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.
添加回答
举报
0/150
提交
取消
