使用 nodejs 加载动态 html

Load dynamic html with nodejs

我是 NodeJs 的新手。
我正在尝试从网站下载一些 html 以便对其进行解析并提供一些信息以进行调试。
我尝试使用 http 模块 (see this post) 成功,但是当我打印块时以这种方式:

var req = http.request(options, function(res) {
    res.setEncoding("utf8");
    res.on("data", function (chunk) {
       console.log(chunk);
    });
});

我没有得到所有使用 ajax 动态加载的 html 例如:

<div class="container">
  ::before
      <div class="row">
        ::before
....
</div>

还有其他 module 可以帮助我实现这个目标吗?

谢谢!

更新

我想与您分享我的成功(感谢@oKonyk)。

请注意,如果您是 运行 本地脚本,则需要设置以下选项:

options = { 'web-security': 'no' };
phantom.create({parameters: options}, function() {});

为了捕获动态构建的页面,您必须在浏览器中呈现它们。使用 node.js.

有多种选择

我建议使用 phantomjs,这是一种所谓的无头浏览器。

为了验证概念,您可以全局安装 npm install phantomjs -g。使用以下内容创建测试脚本 'google.js':

var page = require('webpage').create();
console.log('The default user agent is ' + page.settings.userAgent);
page.settings.userAgent = 'SpecialAgent';
page.open('http://www.google.org', function(status) {
  if (status !== 'success') {
    console.log('Unable to access network');
  } else {
    var html = page.evaluate(function() {
      return document.getElementsByTagName('html')[0].innerHTML;
    });
    console.log(html);
  }
  phantom.exit();
});

然后运行它作为phantomjs google.js

您将打印整个 DOM 页面(至少 <html> 标签内的所有内容),这与您使用 http 模块获得的原始响应不同。

稍后您可以在您的节点项目中使用 phantom(更多信息 here)。