【问题标题】:How to use date.js through Puppeteer exposeFunction?如何通过 Puppeteer exposeFunction 使用 date.js?
【发布时间】:2020-01-12 03:38:13
【问题描述】:

我在这个例子中使用puppeteer 1.19.0date.js 0.3.3

const puppeteer = require('puppeteer');
const date = require('date.js');

let scrape = async () => {
    const browser = await puppeteer.launch({headless: false});
    const page = await browser.newPage();

    await page.exposeFunction('formatDate', (text) =>
    date(text));

    await page.goto('https://www.daraz.com.bd/products/the-vip-suction-mobile-phone-stand-pocket-size-i113492895-s1030756115.html');
    await page.waitFor(1000);

    const result = await page.evaluate(() => {
        let elements = document.querySelectorAll('#module_product_qna > div.pdp-mod-qna > div:nth-child(2) > ul > li')
        for (var element of elements)
        {
            let question = element.querySelector('div:first-of-type > div.qna-content').innerText;
            let qtime = element.querySelector('div:first-of-type > div.qna-meta').innerText;
            let q = qtime.match(/- (.+)/);
            qtime = formatDate(q[1]);         
            return {
                question,
                qtime             
            }
    }});

    browser.close();
    return result;
};

scrape().then((value) => {
    console.log(value);
});

您可以看到我正在尝试使用 date.js 库的日期函数通过 puppeteer exposeFunction 解析相对日期,但日期函数在页面上下文中不起作用。有什么建议我做错了吗?

感谢您的回复!

【问题讨论】:

  • “它不起作用”是什么意思?
  • 我的意思是日期函数在页面上下文之外工作正常。但它在页面评估功能内不起作用。
  • 需要在自己抓取的页面中导入库
  • @Rashomon 你能详细说明一下吗?自己的页面是什么意思?
  • 对不起,没有意识到你已经使用了exposeFunction。您可以尝试使用window.formatDate 访问formatDate 吗?

标签: javascript node.js web-scraping puppeteer


【解决方案1】:

来自木偶师docs

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

试试这个:

const result = await page.evaluate(async() => {
        let elements = document.querySelectorAll('#module_product_qna > div.pdp-mod-qna > div:nth-child(2) > ul > li')
        for (var element of elements)
        {
            let question = element.querySelector('div:first-of-type > div.qna-content').innerText;
            let qtime = element.querySelector('div:first-of-type > div.qna-meta').innerText;
            let q = qtime.match(/- (.+)/);
            qtime = await window.formatDate(q[1]);         
            return {
                question,
                qtime             
            }
    }});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-17
    • 2020-03-27
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    • 2019-09-04
    • 1970-01-01
    • 2018-11-26
    相关资源
    最近更新 更多