我正在抓r / theonion并将标题写入文本文件onion.txt。在那之后,我打算刮掉r / nottheonion并将标题写入文本文件,而不是theonion.txt。我成功写入了onion.txt,但没有写入theonion.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");
});
答案 0 :(得分:2)
使用request-promise
和fs-promise
如果你想要使用promises来简化代码,并使用函数不重复自己。
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));
未经测试。