如何将变量传递到计算函数中?

我试图在Puppeteer中将一个变量传递到一个函数中,但是当我使用以下非常简化的示例时,变量是未定义的。page.evaluate()evalVar

我是Puppeteer的新手,找不到任何可以构建的示例,因此我需要帮助将该变量传递到函数中,以便我可以在其中使用它。page.evaluate()

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();

  }

})();

答案 1

您必须将变量作为参数传递给如下所示:pageFunction

const links = await page.evaluate((evalVar) => {

  console.log(evalVar); // 2. should be defined now
  …

}, evalVar); // 1. pass variable as an argument

您可以通过将更多参数传递给来传入多个变量:page.evaluate()

await page.evaluate((a, b c) => { console.log(a, b, c) }, a, b, c)

参数必须可序列化为浏览器内对象的 JSON 或 JSHandles:https://pptr.dev/#?show=api-pageevaluatepagefunction-args


答案 2

我鼓励你坚持这种风格,因为它更方便可读性更强

let name = 'jack';
let age  = 33;
let location = 'Berlin/Germany';

await page.evaluate(({name, age, location}) => {

    console.log(name);
    console.log(age);
    console.log(location);

},{name, age, location});