本文介绍了Puppeteer:在.evaluate()中传递变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将变量传递到,但当我使用以下非常简化的示例时,变量 evalVar
未定义。
I'm trying to pass a variable into a page.evaluate()
function in Puppeteer, but when I use the following very simplified example, the variable evalVar
is undefined.
我是Puppeteer的新手,无法找到任何构建的示例,所以我需要帮助将该变量传递到 page.evaluate()
函数,所以我可以在里面使用它。
I'm new to Puppeteer and can't find any examples to build on, so I need help passing that variable into the page.evaluate()
function so I can use it inside.
const puppeteer = require('puppeteer');
(async() => {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
const evalVar = 'WHUT??';
try {
await page.goto('https://www.google.com.au');
await page.waitForSelector('#fbar');
const links = await page.evaluate((evalVar) => {
console.log('evalVar:', evalVar); // appears undefined
const urls = [];
hrefs = document.querySelectorAll('#fbar #fsl a');
hrefs.forEach(function(el) {
urls.push(el.href);
});
return urls;
})
console.log('links:', links);
} catch (err) {
console.log('ERR:', err.message);
} finally {
// browser.close();
}
})();
推荐答案
你必须将变量作为参数传递给 pageFunction
像这样:
You have to pass the variable as an argument to the pageFunction
like this:
const links = await page.evaluate((evalVar) => {
console.log(evalVar); // should be defined now
…
}, evalVar);
参数也可以序列化:。
这篇关于Puppeteer:在.evaluate()中传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!