如何将变量传递到评估函数? [英] How can I pass variable into an evaluate function?
本文介绍了如何将变量传递到评估函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将变量传递到page.evaluate()函数中="noreferrer">木偶,但是当我使用以下非常简单的示例时,变量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); // 2. should be defined now
…
}, evalVar); // 1. pass variable as an argument
参数也可以序列化: https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pageevaluatepagefunction-args .
这篇关于如何将变量传递到评估函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文