Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

javascript - NodeJS: Trouble scraping two URLs with promises

I'm scraping r/theonion and writing the titles to a text file, onion.txt. After that, I am intending to scrape r/nottheonion and writing the titles to a text file, nottheonion.txt. I succeed in writing to onion.txt, but not to 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 + '
');
        });
      });
    });

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 + '
');
        });
     });
}, function(err) {
    console.log("Error with scraping r/nottheonion");
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use request-promise and fs-promise to simplify your code if you want to use promises anyway, and use function to not repeat yourself.

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 + '
';
    });
    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));

This is not tested.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...