【问题标题】:image-scraper nodeJS. How to send callback function to result array图像刮板节点JS。如何将回调函数发送到结果数组
【发布时间】:2017-02-26 22:28:51
【问题描述】:

我尝试构建简单的应用程序来构建 img-parser 并开始使用库 image-scraper(node-image-scraper)。并且面临一个问题。问题是:我怎样才能得到最终的对象数组

scraper.scrape(function(image) {
        images_list.push(image);
})

promises - 不起作用,我尝试在函数的参数内部发送回调,但它也没有给我结果。

【问题讨论】:

    标签: javascript node.js web-scraping promise


    【解决方案1】:

    如果你想要一个承诺,那么scraper#scrape() 可以被承诺。

    var Scraper = require("image-scraper");
    
    Scraper.prototype.scrapeAsync = function(ms) {
        var ref = this; // same coding style as in existing methods.
        var images = [];
        return new Promise(function(resolve, reject) {
            ref.on('image', (image) => { images.push(image) });
            ref.on('end', () => { resolve(images) });
            // ref.on('error', reject); // unfortunately image-scraper doesn't emit an 'error' event.
            if(ms !== undefined) { // maybe timeout as substitute for error handler?
                setTimeout(() = {
                    reject(`image-scraper timed out after ${ms} ms`);
                }, ms);
            }
            ref.scrape();
        });
    }
    

    未经测试

    调用,例如:

    const scraper = new Scraper('whatever');
    
    scraper.scrapeAsync(30000).then((images) => {
        // process the `images` array here.
    });
    

    修改图像抓取器源以发出“错误”事件而不是记录错误应该相当简单。您可能需要page_error(致命)和image-error(非致命)的单独事件。

    提交拉取请求似乎没什么意义 - 上次更新是在 2 年前。

    【讨论】:

    • 您认为哪个库更好?或者最好使用“cheerio”或其他东西构建自己的解析器?
    • 我不是真正的专家,但image-scraper 似乎是一个很好的基础。据我所知,错误发射是主要(唯一?)问题。也许开始你自己的分叉 - 当然比从头开始更简单。
    【解决方案2】:

    使用scraper.on 方法监听end 事件。

    请注意,您对.scrape(callback) 的调用也可以替换为.on('image', callback)

    var images = []
    
    scraper.on('image', function (image) {
      images.push(image)
    })
    
    scraper.on('end', function () {
      console.log(images)
    })
    

    【讨论】:

    • 我在函数内部运行此代码 - 它没有生成 console.log(images)。也许我做错了什么?
    猜你喜欢
    • 1970-01-01
    • 2018-10-06
    • 2022-01-03
    • 2019-07-09
    • 2017-02-01
    • 1970-01-01
    • 2018-07-15
    • 2021-08-22
    • 2021-08-17
    相关资源
    最近更新 更多