【问题标题】:Wait for Javascript Web Scraping Function to finish before running for next page?等待 Javascript Web Scraping Function 在运行下一页之前完成?
【发布时间】:2015-01-16 00:08:18
【问题描述】:

我正在尝试创建一个网络爬虫(在 node.js 中),它将从站点中提取信息,并将其写入文件。我已经将它构建为正确地工作在一个页面上,但是当我尝试在 for 循环中使用该函数来迭代多个游戏时,我在所有游戏中都得到了错误的数据。

我知道这与 Javascript 的异步特性有关,并且我已经阅读了回调函数,但我不确定我是否理解如何将它应用到我的代码中。任何帮助将不胜感激:

for(x = 4648; x < 4650; x++){  //iterate over a few gameIDs, used in URL for request
    scrapeGame(x);
}

function scrapeGame(gameId){
    //request from URL, scrape HTML to arrays as necessary
    //write final array to file
}

基本上,我要做的是在 for 循环中,告诉它等待完成 scrapeGame(x) 函数,然后再递增 x 并为下一场游戏运行它——否则,数组开始相互覆盖数据变得一团糟。

编辑:我现在已经包含了我正在尝试运行的完整代码!在写入文件后查看文件时出现错误。例如,第一个文件是 8kb,第二个是 ~16,第三个是 ~32,等等。在运行下一个游戏之前似乎没有清除。

该计划的想法是从存档站点中提取 Jeopardy 问题/答案,以便最终为自己构建一个测验应用程序。

//Iterate over arbitrary number of games, scrape each

for(x = 4648; x < 4650; x++){
    scrapeGame(x, function(scrapeResult) {
        if(scrapeResult){
            console.log('Scrape Successful');
        } else {
            console.log('Scrape ERROR');
        }
    });
}

function scrapeGame(gameId, callback){
    var request = require('request');
        cheerio = require('cheerio');
        fs = require('fs');
        categories = [];
        categorylist = [];
        ids = [];
        clues = [];
        values = ['0','$200','$400','$600','$800','$1000','$400','$800','$1200','$1600','$2000'];
        valuelist = [];
        answers = [];
        array = [];
        file = [];
        status = false;

    var showGameURL = 'http://www.j-archive.com/showgame.php?game_id=' + gameId;
    var showAnswerURL = 'http://www.j-archive.com/showgameresponses.php?game_id=' + gameId;

    request(showGameURL, function(err, resp, body){ 
    if(!err && resp.statusCode === 200){
        var $ = cheerio.load(body);
        //add a row to categories to avoid starting at 0
        categories.push('Category List');
        //pull all categories to use for later
        $('td.category_name').each(function(){
            var category = $(this).text();
            categories.push(category);
        });
        //pull all clue IDs (coordinates), store to 1d array
        //pull any id that has "stuck" in the string, to prevent duplicates
        $("[id*='stuck']").each(function(){
            var id = $(this).attr('id');
            id = id.toString();
            id = id.substring(0, id.length - 6);
            ids.push(id);
            //if single J, pick category 1-6
            if (id.indexOf("_J_") !== -1){
                var catid = id.charAt(7);
                categorylist.push(categories[catid]);
                var valId = id.charAt(9);
                valuelist.push(values[valId]);
            }
            //if double J, pick category 7-12
            else if (id.indexOf("_DJ_") !== -1){
                var catid = parseInt(id.charAt(8)) + 6;
                categorylist.push(categories[catid]);
                var valId = parseInt(id.charAt(10)) + 5;
                valuelist.push(values[valId]);                
            }
            //if final J, pick category 13
            else {
                categorylist.push(categories[13]);
            }
        });
        //pull all clue texts, store to 1d array
        $('td.clue_text').each(function(){
            var clue = $(this).text();
            clues.push(clue);
        });
        //push pulled values to big array
        array.push(ids);
        array.push(categorylist);
        array.push(valuelist);
        array.push(clues);

        //new request to different URL to pull responses
        request(showAnswerURL, function(err, resp, body){ 
            if(!err && resp.statusCode === 200){
                var $ = cheerio.load(body);

                $('.correct_response').each(function(){
                    var answer = $(this).text();
                    answers.push(answer);
                });
                //push answers to big array
                array.push(answers);
                //combine arrays into 1-d array to prep for writing to file
                for(var i = 0; i < array[0].length; i++){
                    var print = array[0][i] + "|" + array[1][i] + "|" + array[2][i] + "|" + array[3][i] + "|" + array[4][i];
                    var stringPrint = print.toString();
                    file.push(stringPrint);
                }
                //update string, add newlines, etc.
                var stringFile = JSON.stringify(file);
                stringFile = stringFile.split('\\').join('');
                stringFile = stringFile.split('","').join('\n');
                //write to file, eventually will append to end of one big file
                fs.writeFile('J_GAME_' + gameId +'.txt', stringFile, function(err) {
                    if(err) {
                        console.log(err);
                    } else {
                        console.log("Game #" + gameId + " has been scraped.");
                        status = true;
                    }
                });
            }
        });
    }
});
        //clear arrays used
        valuelist = [];
        answers = [];
        categories = [];
        categorylist = [];
        ids = [];
        clues = [];
        array = [];
        file = [];
        //feed callback status
        callback(status);
}

【问题讨论】:

    标签: javascript jquery json node.js


    【解决方案1】:
    // Iterate over a few gameIDs, used in URL for request.
    for (x = 4648; x < 4650; x++) {
      // Pass in the callback as an anonymous function.
      // So below I am passing in the id and the function I want to execute.
      // AND, defining the results I am expecting as passed in arguments. 
      scrapeGame(x, function(scrapeResult, err) {
        // This will *NOT* execute *UNTIL* you call it in the function below.
        // That means that the for loop's execution is halted. 
        // This function receives the status that is passed in, 
        // in this case, a boolean true/false and an error if any.
        if (scrapeResult) {
          // Scrape was true, nothing to do.
          // The for loop will now move on to the next iteration.
          console.log('Scrape Successful');
        } else {
          // Scrape was false, output error to console.log and 
          // break loop to handle error.
          console.log('Scrape ERROR :: ' + err);
          // Notice we are calling break while in the 
          // scope of the callback function
          // Remove the break if you want to just move onto
          // the next game ID and not stop the loop
          break;
        }
      });
    }
    
    // This function now accepts two arguments.
    function scrapeGame(gameId, callback) {
    
      // ************************************************
      // ** Do Your Work Here **
      // Request from URL, scrape HTML to arrays as necessary.
      // Write final array to file.
      // After file creation, execute the callback and pass bool
      // status (true/false).
      // ************************************************
    
      var request = require('request'),
          cheerio = require('cheerio'),
          fs = require('fs'),
          categories = [],
          categorylist = [],
          ids = [],
          clues = [],
          values = [
              '0',
              '$200',
              '$400',
              '$600',
              '$800',
              '$1000',
              '$400',
              '$800',
              '$1200',
              '$1600',
              '$2000'
          ],
          valuelist = [],
          answers = [],
          array = [],
          file = [],
          showGameURL = 'http://www.j-archive.com/showgame.php?game_id=' + gameId,
          showAnswerURL = 'http://www.j-archive.com/showgameresponses.php?game_id=' + gameId;
    
      request(showGameURL, function(err, resp, body) {
        if (!err && resp.statusCode === 200) {
          var $ = cheerio.load(body);
          //add a row to categories to avoid starting at 0
          categories.push('Category List');
          //pull all categories to use for later
          $('td.category_name').each(function() {
            var category = $(this).text();
            categories.push(category);
          });
          //pull all clue IDs (coordinates), store to 1d array
          //pull any id that has "stuck" in the string, to prevent duplicates
          $("[id*='stuck']").each(function() {
            var id = $(this).attr('id');
            id = id.toString();
            id = id.substring(0, id.length - 6);
            ids.push(id);
            //if single J, pick category 1-6
            if (id.indexOf("_J_") !== -1) {
              var catid = id.charAt(7);
              categorylist.push(categories[catid]);
              var valId = id.charAt(9);
              valuelist.push(values[valId]);
            }
            //if double J, pick category 7-12
            else if (id.indexOf("_DJ_") !== -1) {
              var catid = parseInt(id.charAt(8)) + 6;
              categorylist.push(categories[catid]);
              var valId = parseInt(id.charAt(10)) + 5;
              valuelist.push(values[valId]);
            }
            //if final J, pick category 13
            else {
              categorylist.push(categories[13]);
            }
          });
          //pull all clue texts, store to 1d array
          $('td.clue_text').each(function() {
            var clue = $(this).text();
            clues.push(clue);
          });
          //push pulled values to big array
          array.push(ids);
          array.push(categorylist);
          array.push(valuelist);
          array.push(clues);
    
          //new request to different URL to pull responses
          request(showAnswerURL, function(err, resp, body) {
            if (!err && resp.statusCode === 200) {
              var $ = cheerio.load(body);
    
              $('.correct_response').each(function() {
                var answer = $(this).text();
                answers.push(answer);
              });
              //push answers to big array
              array.push(answers);
              //combine arrays into 1-d array to prep for writing to file
              for (var i = 0; i < array[0].length; i++) {
                var print = array[0][i] + "|" + array[1][i] + "|" + array[2][i] + "|" + array[3][i] + "|" + array[4][i];
                var stringPrint = print.toString();
                file.push(stringPrint);
              }
              //update string, add newlines, etc.
              var stringFile = JSON.stringify(file);
              stringFile = stringFile.split('\\').join('');
              stringFile = stringFile.split('","').join('\n');
              //write to file, eventually will append to end of one big file
              fs.writeFile('J_GAME_' + gameId + '.txt', stringFile, function(err) {
    
                //clear arrays used
                valuelist = [];
                answers = [];
                categories = [];
                categorylist = [];
                ids = [];
                clues = [];
                array = [];
                file = [];
    
                if (err) {
                  // ******************************************
                  // Callback false with error.
                  callback(false, err);
                  // ******************************************
                } else {
                  console.log("Game #" + gameId + " has been scraped.");
                  // ******************************************
                  // Callback true with no error. 
                  callback(true);
                  // ******************************************
                }
              });
            }
          });
        }
      });
    }
    

    【讨论】:

    • 在我的情况下,数据是我想要写入相关文件的字符串——所以在回调内部,我会实际写入文件吗?还是我在回调之外写入文件,而我传回回调的内容并不重要?
    • 不,没关系,我编辑了我的答案。让我知道它是否与您的情况更相关。
    • 这似乎将状态传回给回调,但我没有用它做任何事情——我不需要说“如果是假的,不要做下一个”然而?”我想我不明白回调是如何阻止函数的下一次调用在它第一次完成之前发生的。
    • 通过添加回调,您将“暂停” for 循环的执行。它必须等待传入到 scrapeGame 的回调代码执行,然后才能进入循环的下一次迭代,并且在 scrapeGame 函数结束之前我们不会这样做。
    • 我收到 Scrape ERROR -- 我将callback(status); 作为scrapeGame 函数的最后一行。看起来不管callback(status)返回什么,它仍然在处理我在for循环中要求的scrapeGame的每一次迭代。
    【解决方案2】:

    我的假设是您希望它们一个接一个地被刮掉,而不是并行地。所以, for 循环将无济于事。以下方法应该可以解决问题:

        var x = 4648;
        var myFunc = scrapeGame(x, function cb(){
            if(x >= 4650){
               return; 
            }
            x++;
            return myFunc(x, cb); 
        });
    
    
    
    function scrapeGame(gameId){
        //request from URL, scrape HTML to arrays as necessary
        //write final array to file
    }
    

    对于嵌套异步函数,您希望它们以串行方式执行,您应该忘记 for 循环。

    使用 http 客户端正确处理请求的示例:

    function scrapeGame(gameId, cb){
    
    //your code and set options
    
    http.request(options, function(response){
        var result = "";
        response.on('data', function (chunk) {
                    result += chunk;
                 });
        response.on('end',function(){
                   //write data here;
    
                   //do the callback
                   cb();    
                });
    });
    
    }
    

    【讨论】:

    • 这确实以串行方式执行它们(即以正确的顺序),但由于 scrapeGame 函数有一个 HTTP 请求,似乎它们之前没有让新请求完全加载它继续。这导致我的数据在将下一个游戏写入文件之前没有被正确清除——第一个游戏看起来很完美。在那之后,它是一团糟。
    • 您似乎没有正确处理响应?共享该功能的代码会很有帮助。但是,我添加了更多代码 sn-p 来向您展示应该如何处理每个响应数据。数据以块的形式出现,您必须收集它们直到所有块都进来,然后您才应该继续/为下一个请求进行回调。
    • 分享该函数的代码会很有帮助。 +1:D
    • 在我做一些清理之后我会更新我上面的代码——谢谢你们到目前为止的帮助!
    【解决方案3】:

    我解决了我看到的问题的根本原因,但我相信如果没有上面 red 的回调帮助,我也会迷失方向。

    事实证明数据处理正确,但文件写入混乱。原来有一个不同的方法可以调用而不是 writeFile 或 appendFile:

    fs.appendFileSync();

    调用同步版本以附加到文件的顺序处理对文件的写入,而不是直接执行。除了上面的回调帮助之外,这解决了这个问题。

    感谢大家的帮助!

    【讨论】:

    • 很高兴你把它整理好了!
    猜你喜欢
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-25
    • 2021-01-03
    • 2021-07-30
    • 2017-12-21
    • 1970-01-01
    相关资源
    最近更新 更多