首页 > 解决方案 > Pass variable into page.evaluate

问题描述

I have searched for passing variables, but I'm not successful. It returns the 'data' as undefined. Please help me to fix this!

const details = (
      await Promise.allSettled(
        datas
          .map(async (data) => {
            const page = await browser.newPage();

            await page.goto(data.link, {
              waitUntil: "networkidle2",
            });
            return await page.evaluate((data) => {
              return {
                regular_price: document.querySelector(data.regular_price_class)
                  ? document.querySelector(data.regular_price_class).innerText.replace(/[\$,\D]/g, "")
                  : "",
                sale_price: document.querySelector(data.sale_price_class)
                  ? document.querySelector(data.sale_price_class).innerText.replace(/[\$,\D]/g, "")
                  : "",
                online_sale_price: document.querySelector(data.online_sale_price_class)
                  ? document.querySelector(data.online_sale_price_class).innerText.replace(/[\$,\D]/g, "")
                  : "",
                promotion: document.querySelector(data.promotion_class)
                  ? document.querySelector(data.promotion_class).innerText.replace(/[\$,\D]/g, "")
                  : "",
              };
            });
          }, data)
      )
    )

标签: javascriptasync-awaitpromisepuppeteer

解决方案


现在,您将data作为第二个参数传递给.map,这没有意义:

const details = (
    await Promise.allSettled(
      datas
        .map(async (data) => {
          // ...
        }, data)
    )
  )

相反,您需要将其传递给page.evaluate

const details = (
    await Promise.allSettled(
      datas
        .map(async (data) => {
          const page = await browser.newPage();

          await page.goto(data.link, {
            waitUntil: "networkidle2",
          });
          return await page.evaluate((data) => {
            return {
              // ...
            };
          }, data);
        })
    )
  )

我还推荐一个提取价格的函数,让事情变得更加干燥:

return page.evaluate((data) => {
    const getPrice = selector => (document.querySelector(selector)?.innerText || '').replace(/[\$,\D]/g, "");
  return {
      regular_price: getPrice(data.regular_price_class),
      sale_price: getPrice(data.sale_price_class),
      online_sale_price: getPrice(data.online_sale_price_class),
      promotion: getPrice(data.promotion_class),
  };
}, data);

推荐阅读