【问题标题】:node js crawler and expressenode js爬虫和expresse
【发布时间】:2020-11-21 10:12:33
【问题描述】:

我想知道如何在使用 npm crawler 爬取后发送结果。 我收到了这个错误

错误 [ERR_HTTP_HEADERS_SENT]:发送到客户端后无法设置标头

有什么帮助吗?

app.get('/', async (req, result) => {
    var c = new Crawler({
        maxConnections: 10,
        callback: function(error, res, done) {
            if (error) {
                console.log(error);
            } else

            {
                var $ = res.$;
                $('.ajax_block_product').each(function(i, elem) {
                    var x = $(elem)
                    produit.site = x.find('a').attr('href').split('w.').pop().split('.tn')[0];
                    produit.image = x.find('img').attr('src');
                    produit.lien = x.find('a').attr('href');
                    produit.Nom_produit = x.find('a').attr('title');
                    produit.Prix = x.find('span.price').text();
                    produit.Etat = x.find('span.available-now').text();
                    produits.push(produit);

                });
                $('.item-product').each(function(i, elem) {
                    var x = $(elem)
                    produit.site = x.find('a').attr('href').split('w.').pop().split('.tn')[0];
                    produit.image = x.find('img').attr('src');
                    produit.lien = x.find('a').attr('href');
                    produit.Nom_produit = $(x.find('a')).find('p').text().substr(0, 27);
                    produit.Prix = x.find('span.price').text();
                    produit.Etat = x.find('span.available-now').text();
                    produits.push(produit);


                });
                console.log(produits)
                result.send(produits)
            }
            done();

        },
    })

    c.queue([url1, url2, url3, url4])

})

【问题讨论】:

    标签: node.js web-crawler


    【解决方案1】:

    您可以将res.headers({}) 下的标头设置为对象,您可以在此处找到更多信息:https://www.npmjs.com/package/crawler#callbacks

    另外,我建议您将代码设置在else 范围内,这样它只会在没有错误时运行代码。

    为了消除另一个错误来源,您可能希望放弃您在第 1 行中使用app.get 执行的 REST API,我只需通过在本地调用它来测试它来正常运行该命令。

    【讨论】:

    • 好的,但是我应该如何将结果发送到网络客户端(角度)
    • 我只是建议在你使用前端之前这样做,这个想法是在本地制作一个 POC(概念证明),没有太多其他代码围绕它,尤其是像爬行这样的东西,这更多往往那么不会厌倦。稍后我会将爬虫打包到另一个文件中,然后调用app.get()中的函数,以防止代码混乱。
    猜你喜欢
    • 2019-11-07
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 2019-06-24
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多