如何在`await page.evaluate(indexTotal => {`在Puppeteer中使用)中现有的功能global.parseData(id,name,url)?

时间:2019-09-21 11:00:28

标签: javascript node.js puppeteer

问题:

page.evaluate中使用我的global.parseData函数的正确语法是什么?


编辑:

当前代码:

getData.js

    getData: function() {

            let getData = async () => {
                url = 'url';

                await page.exposeFunction('parseData', (items2, items3, item2, ...) => global.parseData(items2, items3, item2, ...));

                const thedata = await page.evaluate( async() => {

                    var items = [];
                    var items2 = [];
                    var items3 = [];

                    $('.htmlElement').find('.childElements').each(function(ind) {
                        ...

                        var returnedObject = await window.parseData(items2, items3, item2, ...);

                        items.push(returnedObject.item);
                        items2 = returnedObject.items2;
                        items3 = returnedObject.items3;

                    });

                    var largeObject = {
                        items: items,
                        items2: items2,
                        items3: items3
                    }

                    console.log("RETURNED OBJECT: "+JSON.stringify(returnedObject));

                    return largeObject;

                }).catch( error => {
                    console.log("ERROR: "+error);
                });

                browser.close();
                return thedata;
            }

            getData().then(largeObject => {

                global.saveData(largeObject);

            });
    }

app.js

global.parseData = function(items2, items3, item2, ...) {

    ...


    if(!item2 || item2 == "") {
        ...
    }
    else {
        items2.push(item2);
        var item3 = ...;
        items3.push(item3);
    }

    var item = {
        ...
    }

    var largeObject = {
        item: item,
        items2: items2,
        items3: items3
    }

    console.log("LARGE OBJECT: "+JSON.stringify(largeObject));

    return largeObject;
}

控制台日志输出:

RETURNED OBJECT: {}
LARGE OBJECT: {data}
RETURNED OBJECT: {}
RETURNED OBJECT: {}
RETURNED OBJECT: {}

1 个答案:

答案 0 :(得分:1)

问题

该错误来自此部分代码:

page.evaluate((global.parseData(id,name,url)) //...

您必须先使用参数将函数传递给page.evaluate。您将在此处传递参数和函数调用的组合。

解决方案

要在浏览器上下文中使用Node.js环境中的功能,您需要使用page.exposeFunction公开它。

代码示例

// expose the function to the page
await page.exposeFunction('parseData', (id, name, url) => {
    // do calculations
    return 'RESULT';
});

// Alternative: Call another function
await page.exposeFunction('parseData2', (id, name, url) => global.parseData(id,name,url));

// run code inside the page
await page.evaluate(async (indexTotal) => {
    // run code inside the page, set variables
    // ...
    const result = await window.parseData(id, name, url); // call your Node.js function
}, indexTotal);