Javascript 使用nodejs加载动态html

Javascript 使用nodejs加载动态html,javascript,ajax,node.js,http,httprequest,Javascript,Ajax,Node.js,Http,Httprequest,我对NodeJs很陌生。 我试图从一个网站下载一些html,以便对其进行解析,并提供一些信息供调试。 我尝试使用http模块获得成功,但在打印区块时采用这种方式: var req = http.request(options, function(res) { res.setEncoding("utf8"); res.on("data", function (chunk) { console.log(chunk); })

我对NodeJs很陌生。 我试图从一个网站下载一些html,以便对其进行解析,并提供一些信息供调试。 我尝试使用http模块获得成功,但在打印区块时采用这种方式:

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>

为了捕获动态构建的页面,您必须在浏览器中呈现它们。使用node.js有几个选项可以做到这一点

我建议使用,这就是所谓的无头浏览器

为了证明这个概念,您可以在全局范围内安装npm安装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,至少是标记中的所有内容,这与使用http模块得到的原始响应不同


稍后,您可以在节点项目中使用phantom了解更多信息。

谢谢您的回答@oKonyk。使用此解决方案,我得到幻象stdout:NETWORK\u ERR:XMLHttpRequest异常101:同步请求中发生网络错误。我正在从localhost运行脚本,所以我想我必须设置-websecurity=false,不是吗?在哪里可以设置此选项?我正在用节点运行脚本。我创建了幻影。创建{'web-security':'no'},函数ph{};但是错误仍然出现!那么您试图访问的URL是localhost?如果它只是任何公共URL,我可以尝试从我的系统访问它。。。当您说您使用node运行脚本时,您的意思是您的phantomjs进程作为主节点脚本上的子进程吗?
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();
});