How to put scraping content to html (Node.js, chee

2019-07-15 09:50发布

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条回答
我命由我不由天
2楼-- · 2019-07-15 10:42
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);
查看更多
登录 后发表回答