木偶-使用瞬间评估页面

时间:2019-06-01 15:53:54

标签: javascript momentjs puppeteer

我正在尝试使用"puppeteer": "^1.16.0","moment": "^2.24.0",。当运行page.evaluate()时,我将字符串转换为日期obj时得到

  

错误:评估失败:ReferenceError:未定义时刻

在下面的最小示例中查找:

const puppeteer = require("puppeteer-extra")
const moment = require('moment')

function shuffle(dataObjArr) {
    let res = dataObjArr.sort(() => Math.random() - 0.5);
    return res
}

let issuerUrls = JSON.parse('[{"id":62,"name":"Product 1","ecomUrl":"/product/252","createdAt":"2019-05-25T07:51:49.000Z","updatedAt":"2019-05-25T07:51:49.000Z"},  {"id":15,"name":"Product 2","ecomUrl":"/product/251","createdAt":"2019-05-25T07:51:49.000Z","updatedAt":"2019-05-25T07:51:49.000Z"}]')

let issuerUrlsShuffled = shuffle(issuerUrls)
let BASE_URL = "https://www.webscraper.io/test-sites/e-commerce/allinone"
// puppeteer usage as normal
puppeteer.launch({
    headless: false,
    args: ["--disable-notifications"]
}).then(async browser => {
    const page = await browser.newPage()
    await page.setViewport({
        width: 800,
        height: 600
    })

    for (let i = 0; i < issuerUrlsShuffled.length; i++) {
        try {

            let URL = BASE_URL + issuerUrlsShuffled[i].ecomUrl;

            await page.goto(URL)

            page.waitForNavigation({
                timeout: 60,
                waitUntil: 'domcontentloaded'
            });

            const data = await page.evaluate(() => {

                const priceData = []

                let date = "9/23/2016" // this is needed for testing purposes only!!!

                priceData.push({
                    price_date: moment(date, 'M/DD/YYYY').toDate()
                })
                return priceData
            }, moment)

            // show data
            console.log(JSON.stringify(data, null, 2))

            await page.waitFor(3000)
        } catch (error) {
            console.log(error)
        }
    }
    await browser.close()
})

如您所见,我尝试将moment实例传递给evaluate函数,但是仍然出现错误。

有人建议我在做什么错吗?

感谢您的答复!

1 个答案:

答案 0 :(得分:1)

您只能将可序列化的数据作为参数传递给page.evaluate函数。 (有关更多信息,请参见docs)。由于moment是一个函数,并且一个函数无法序列化,因此无法轻松使用它。

要从Node.js环境向页面公开功能,可以使用page.exposeFunction。引用文档:

  

该方法在页面的name对象上添加了一个名为window的函数。调用该函数时,该函数在node.js中执行puppeteerFunction并返回一个Promise,该Promise解析为返回值puppeteerFunction

代码示例:

Node.js环境中的以下代码设置了一个函数formatDate,该函数返回格式化的日期:

await page.exposeFunction('formatDate', (date) =>
  moment(date, 'M/DD/YYYY').toDate()
);

然后您的操纵p代码可以使用如下功能:

const data = await page.evaluate(async () => {
  const priceData = []
  let date = "9/23/2016"
  priceData.push({
    price_date: await window.formatDate(date)
  })
  return priceData
})
相关问题