问题
i need to scrapping some content, and added it to my html file.
var request = require('request');
var cheerio = require('cheerio');
setInterval(function () {
request('https://2ch.hk/rf/res/1490589.html', function (error, response, html) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(html);
$('.post-message').each(function (i, element) {
var a = $(this).text();
console.log(a);
});
}
});
}, 5000);
Now, i have a parsed page to my console. But i dont understand, how to put in to html. Help!
回答1:
var request = require('request');
var cheerio = require('cheerio');
var fs = require('fs');
var path = require('path');
var $$ = cheerio.load(fs.readFileSync('./index.html'));
setInterval(function () {
request('https://2ch.hk/rf/res/1490589.html', function (error, response, html) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(html), text = [];
$('.post-message').each(function (i, element) {
$$('ul').append('<li>' + $(this).text().trim() + '</li>');
});
fs.writeFileSync(path.join(process.cwd(), 'index.html'), $$.html(), {'encoding': 'utf-8'});
}
});
}, 5000);
来源:https://stackoverflow.com/questions/26963389/how-to-put-scraping-content-to-html-node-js-cheerio