【问题标题】:Node .JS Crawler to JSON output is empty节点 .JS 爬虫到 JSON 输出为空
【发布时间】:2017-04-01 10:26:54
【问题描述】:

所以我正在尝试使用 Node.js。我想构建一个简单的爬虫来扫描页面,然后将所有链接返回到 json 文件中。但是,当我运行脚本时,它返回 0 个链接。

这是我的完整代码:

    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 写入文件的奖励积分:)

【问题讨论】:

    标签: json node.js dom web-crawler


    【解决方案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");
        }
    });
    

    【讨论】:

    • 这表示文件成功购买然后没有做任何事情。我将“/tmp/test”更改为“test.json”,它起作用了。
    猜你喜欢
    • 2015-01-27
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多