2017-04-01 52 views
0

所以我想在Node.js上工作。我想构建一个简单的抓取程序,它扫描页面,然后将所有链接返回到json文件中。但是,当我运行该脚本时,它返回0链接。节点.JS Crawler到JSON输出为空

这里是将其全部我的代码:

var request = require('request'); 
    var cheerio = require('cheerio'); 
    var fs = require("fs"); 

    var url = 'https://stackoverflow.com/questions'; 

    //Create the blank array to fill: 
    var obj = { 
     table: [] 
    }; 

    var i = 0; 

    request(url, function(err, resp, body){ 
     $ = cheerio.load(body); 
     links = $('a'); //jquery get all hyperlinks 

     $(links).each(function(i, link){ 
     var actualLink = $(link).attr('href'); 
      obj.table.push({id: i, url:actualLink}); //add some data 
      i++; 
     }); 

    }); 

    var json = JSON.stringify(obj); 

    console.log(json); 

在终端的输出是这样:

$ !!

节点nodetest.js

{ “表”:[]}

任何人都可以看到这是为什么空白?写的最后JSON到一个文件:

回答

1

您必须使用obj请求的成功回调奖励积分,这就是它被填充:

request(url, function(err, resp, body) { 
    $ = cheerio.load(body); 
    links = $('a'); //jquery get all hyperlinks 

    $(links).each(function(i, link) { 
     var actualLink = $(link).attr('href'); 
     obj.table.push({id: i, url:actualLink}); //add some data 
    }); 

    // Only here you can be sure that the "obj" variable is properly 
    // populated because that's where the HTTP request completes 
    var json = JSON.stringify(obj); 
    console.log(json); 
}); 

在你的代码都放在console.log以外的请求成功异步,因此obj变量尚未填充。

另请注意,您不需要i变量。它会自动传递给each回调函数,您不需要明确声明或递增它。

至于将结果写到一个文件的问题,你可以使用fs.writeFile功能:

fs.writeFile("/tmp/test", json, function(err) { 
    if(!err) { 
     console.log("File successfully saved"); 
    } 
}); 
+0

这是说文件成功买入,然后什么也没做。我将“/ tmp/test”更改为“test.json”,它工作。 – JamesG