Scraping JavaScript-generated website with Node.js

佐手、 提交于 2019-12-13 00:26:48

问题


When I parse a static html page, my node.js app works well. However, when the url is a JavaScript-generated page, the app doesn't work. How can I scrape a JavaScript-generated web page?

My app.js

var express = require('express'),
  fs = require('fs'),
  request = require('request'),
  cheerio = require('cheerio'),
  app = express();

app.get('/scrape', function( req, res ) {

  url = 'http://www.apache.org/';

  request( url, function( error, response, html ) {
    if( !error ) {
      var $ = cheerio.load(html);

      var title, release, rating;
      var json = { title : "" };

      $('body').filter(function() {
        var data = $(this);
        title = data.find('.panel-title').text();
        json.title = title;
      })
    }

    fs.writeFile('output.json', JSON.stringify(json, null, 4), function(err) {
      console.log( 'File successfully written! - Check your project directory for the output.json file' );
    });

    // Finally, we'll just send out a message to the browser reminding you that this app does not have a UI.
    res.send( 'Check your console!' );
  });
});

app.listen('8081');
console.log('Magic happens on port 8081');
exports = module.exports = app;

回答1:


Cheerio won't execute the javascript on the page as it's just made for parsing plain HTML.

I'd suggest a different approach using something like PhantomJS: http://phantomjs.org/



来源:https://stackoverflow.com/questions/30479141/scraping-javascript-generated-website-with-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!