Promise爬虫NodeJS的递归循环

时间:2018-11-27 00:13:58

标签: javascript node.js loops recursion promise

我正在尝试使用递归循环和Promises来刮擦网站。 但是它失败了。它只在第一页发出请求,在第二页程序停止向我发送未处理的承诺拒绝警告

我有这三个JS文件:

  1. scrapeAll.js(是调用scrapePage.js的递归循环)
  2. scrapePage.js
  3. scrapeComponents.js

scrapeAll.js:

var indexPage = 0;

scrapePage(indexPage).then((json)=>{
    console.log(JSON.stringify(json, null, 4));
    if(indexPage === Number.MAX_SAFE_INTEGER){
        console.log("MAX SAFE INTEGER");
        return;
    }
    save(json);
    indexpage++;
    scrapePage(indexPage);
}).catch((data)=>{
    console.log(data);
    if(indexPage === Number.MAX_SAFE_INTEGER){
        console.log("MAX SAFE INTEGER");
        return;
    }
    indexPage++;
    scrapePage(indexPage);
});

ScrapePage.JS

let makeRequestCounter = 0;


function scrapePage(number) {
    return new Promise((resolve, reject) => {

        let url = URL + number;

        let options = {
            url: url,
            headers: {
                Host: SITE,
                Connection: "keep-alive",
                Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
                "Accept-Language": "it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7",
                "Cache-Control": "max-age=0",
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36",
                "Cookie": restoreCookieToString()
            }
        };

        makeRequest(options).then((jsonData) => {
            resolve(jsonData);
        }).catch((error) => {
                //REQUEST_LIMIT_EXCEEDED
                if (error === CONSTANTS.REQUEST_LIMIT_EXCEEDED) {
                    reject(CONSTANTS.REQUEST_LIMIT_EXCEEDED);
                }

                //ALREADY_EXIST
                else if (error === CONSTANTS.ALREADY_EXIST) {
                    reject(CONSTANTS.ALREADY_EXIST);
                }

                else if (error === 404) {
                    reject("no data found at this page");
                }

                //error can beeconnrefused or econnreset
                else if (error.code !== undefined) {

                    //econnrefused
                    if (error.code === CONSTANTS.ECONNREFUSED) {
                        reject("WRONG_URL", url);
                    }

                    //econnreset
                    else if (error.code === CONSTANTS.ECONNRESET) {
                        console.log("\neconnreset error\n");
                        makeRequest(options);
                    }

                }
            }
        );
    });
}

function makeRequest(options) {
    return new Promise((resolve, reject) => {

        let json = {
            category: [],
            imgs: [],
            title: "",
            description: "",
            url: ""
        };


        if (makeRequestCounter === CONSTANTS.REQUEST_LIMIT) {
            reject(CONSTANTS.REQUEST_LIMIT_EXCEEDED);
        }

        makeRequestCounter++;

        console.log("request to: ", options.url);


        request(options, function (error, response, html) {
            if (error) {
                //error: possible econnreset econnrefused
                reject(error);

            } else {

                if (response.statusCode === 200) {
                    cookieSave(response.headers);


                    //---------- check if in db the url is already saved -------------//

                    check(response.request.uri.href, (err) => {
                        if (!err) {
                            reject(CONSTANTS.ALREADY_EXIST);
                        }
                    });

                    //----------finish checking, is new -------------------//


                    //GETTING TITLE

                    title(html, json_recipe).then((json) => {

                            //GETTING category

                            category(html, json).then((json) => {

                                    //GETTING images

                                    imgs(html, json).then((json) => {


                                        description(html, json).then((json) => {


                                                    json.url = response.request.uri.href;

                                                    resolve(json);

                                            //description error
                                        }).catch((error) => {
                                            console.log(error);
                                        });

                                        //images error
                                    }).catch((error) => {
                                        console.log(error);
                                    });

                                //category error
                            }).catch((error) => {
                                console.log(error);
                            });
                            //title error
                        }
                    ).catch((error) => {
                        console.log(error);
                    });
                }

                //no data in this page
                if (response.statusCode === 404) {
                    reject(response.statusCode);
                }
            }

        });
    });
}

scrapeComponents.js

...

function description(html, json) {
return new Promise((resolve, reject) => {

    const $ = cheerio.load(html);

    let description = $('.submitter__description').text().trim();

    json.description = JSON.parse(description);

    resolve(json);

});

}
...

错误:

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): no data found at this page

程序发出第一个请求,并正确地在scrapeAll.js处正确返回scrapePage(indexPage = 1)。 我的程序第二次执行与第一次完全相同的操作,但是什么时候该返回到scrapeAll.js(ScrapePage.js中为reject(“在此页面上未找到数据”);),该程序以错误结束。 两个页面都没有数据,但是程序也失败了,好的页面只保存了第一页。 我认为我在诺言方面犯了一个大错误。 非常感谢你们。

2 个答案:

答案 0 :(得分:1)

问题是您在scrapePage(indexPage)中对scrapeAll.js的一个或多个调用失败。您无法像使用其他代码那样递归地调用promise,因此在其他调用上也需要.then.catch。将.catch添加到其他调用中将使您看到真正的故障根源。

scrapePage(indexPage)
  .then((json)=>{
    console.log(JSON.stringify(json, null, 4));
    if(indexPage === Number.MAX_SAFE_INTEGER){
      console.log("MAX SAFE INTEGER");
      return;
    }
    save(json);
    indexpage++;
    scrapePage(indexPage).catch(e => console.log(e));
  })
  .catch((data)=>{
    console.log(data);
    if(indexPage === Number.MAX_SAFE_INTEGER){
      console.log("MAX SAFE INTEGER");
      return;
    }
    indexPage++;
    scrapePage(indexPage).catch(e => console.log(e));
});

答案 1 :(得分:1)

您对scrapPage函数的调用仅运行一次,并且您没有迭代调用它。您可能必须使用函数在迭代中调用它。更新您的scrapeAll.js:

    function callScrapPage() {
    var indexPage = 0;
    while (indexPage < Number.MAX_SAFE_INTEGER) {
        scrapePage(indexPage).then((json) => {
            console.log(JSON.stringify(json, null, 4));
            save(json);
            indexpage++;
         }
       }
   }