【问题标题】:Scraping JavaScript-generated website with Node.js使用 Node.js 抓取 JavaScript 生成的网站
【发布时间】:2015-08-09 08:13:47
【问题描述】:

当我解析静态 html 页面时,我的 node.js 应用程序运行良好。但是,当 url 是 JavaScript 生成的页面时,应用程序将无法运行。如何抓取 JavaScript 生成的网页?

我的 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;

【问题讨论】:

标签: javascript node.js express web-scraping cheerio


【解决方案1】:

Cheerio 不会执行页面上的 javascript,因为它只是用于解析纯 HTML。

我建议使用 PhantomJS 之类的不同方法:http://phantomjs.org/

【讨论】:

  • 我正在做一个项目并且遇到了同样的问题。我一直在研究 phantom.js 来帮助解决这个问题。有什么地方可以指点我吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-09
  • 1970-01-01
  • 2014-08-08
  • 2014-04-07
相关资源
最近更新 更多