【问题标题】:NodeJS: Trouble scraping two URLs with promisesNodeJS:无法使用 Promise 抓取两个 URL
【发布时间】:2017-05-09 09:37:37
【问题描述】:

我正在抓取 r/theonion 并将标题写入文本文件 onion.txt。之后,我打算抓取 r/nottheonion 并将标题写入文本文件 nottheonion.txt。我成功地写入了 onion.txt,但没有写入 nottheonion.txt。

var onion_url = "https://www.reddit.com/r/theonion";
var not_onion_url = "https://www.reddit.com/r/nottheonion";

var promise = new Promise(function(resolve, reject) {

    request(onion_url, function(error, response, html) {
        if (error) {
            console.log("Error: " + error);
        }

        var $ = cheerio.load(html);

        $("div#siteTable > div.link").each(function(idx) {
            var title = $(this).find('p.title > a.title').text().trim();
            console.log(title);

            fs.appendFile('onion.txt', title + '\n');
        });
      });
    });

promise.then(function(result) {
    request(not_onion_url, function(error, response, html) {
        if (error) {
            console.log("Error: " + error);
        }

        var $ = cheerio.load(html);

        $("div#siteTable > div.link").each(function(idx) {
            var title = $(this).find('p.title > a.title').te .   xt().trim();
            console.log(title);

            fs.appendFile('not_onion.txt', title + '\n');
        });
     });
}, function(err) {
    console.log("Error with scraping r/nottheonion");
});

【问题讨论】:

  • 但不是 nottheonion.txt,你一定遇到了一些错误?你试过调试吗?
  • 你没有打电话给resolve of promie

标签: javascript node.js


【解决方案1】:

使用request-promisefs-promise 来简化你的代码,如果你还是想使用promise,并使用函数来避免重复自己。

var rp = require('request-promise');
var fsp = require('fs-promise');

var onion_url = "https://www.reddit.com/r/theonion";
var not_onion_url = "https://www.reddit.com/r/nottheonion";

function parse(html) {
    var result = '';
    var $ = cheerio.load(html);
    $("div#siteTable > div.link").each(function(idx) {
        var title = $(this).find('p.title > a.title').text().trim();
        console.log(title);
        result += title + '\n';
    });
    return result;
}

var append = file => content => fsp.appendFile(file, content);

rp(onion_url)
  .then(parse)
  .then(append('onion.txt'))
  .then(() => console.log('Success'))
  .catch(err => console.log('Error:', err));

rp(not_onion_url)
  .then(parse)
  .then(append('not_onion.txt'))
  .then(() => console.log('Success'))
  .catch(err => console.log('Error:', err));

这未经测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 2014-02-12
    • 2020-06-08
    相关资源
    最近更新 更多