使用 phantomjs 获取 javascript 渲染的 html 源

Get javascript rendered html source using phantomjs

首先,我不是在寻求开发或测试环境方面的帮助。我也是 phantomjs 的新手,我想要的只是 phantomjs 在 linux 终端上的命令行操作。

我有一个 html 页面,其正文由一些 javascript 代码呈现。我需要的是我想使用 phantomjs 下载呈现 html 的内容。

我不知道使用 phantomjs。我在 shell 脚本方面有一些经验。所以我尝试用 curl 来做到这一点。但由于 curl 不足以呈现 javascript,我只能获得默认源代码的 html。未下载呈现的内容。我听说 ruby mechanize 可以做这个工作。但是我对ruby一无所知。因此,在进一步调查中,我找到了命令行工具 phantomjs。我如何使用 phantomjs 执行此操作?

请随时询问我需要提供哪些额外信息。

不幸的是,仅使用 PhantomJS 命令行是不可能的。你必须使用 Javascript 文件才能真正用 PhantomJS 完成任何事情。

这是您可以使用的非常简单的脚本版本

大部分代码复制自

printSource.js

var system = require('system');
var page   = require('webpage').create();
// system.args[0] is the filename, so system.args[1] is the first real argument
var url    = system.args[1];
// render the page, and run the callback function
page.open(url, function () {
  // page.content is the source
  console.log(page.content);
  // need to call phantom.exit() to prevent from hanging
  phantom.exit();
});

将页面源打印到标准输出。

phantomjs printSource.js http://todomvc.com/examples/emberjs/

将页面源保存在文件中

phantomjs printSource.js http://todomvc.com/examples/emberjs/ > ember.html

var pagehtml = page.evaluate("function() {"+ 
  "return '<html><head>' + document.head.innerHTML + '</head>' + '<body>' + document.body.innerHTML + '</body></html>';" + 
"}");


fs.write('output.html',pagehtml,'w');