使用phantomjs获取javascript呈现的html源代码

时间:2015-01-29 07:52:55

标签: javascript html shell phantomjs

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

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

我不知道使用phantomjs。我在shell脚本方面有一些经验。所以我试图用curl做到这一点。但由于curl不足以呈现javascript,我只能获取默认源代码的html。渲染的内容未下载。我听说ruby机械化可以做这个工作。但我不知道红宝石。因此,在进一步调查中,我找到了命令行工具phantomjs。如何使用phantomjs

执行此操作

请随时询问我需要提供的所有其他信息。

2 个答案:

答案 0 :(得分:15)

不幸的是,仅使用PhantomJS命令行是不可能的。您必须使用Javascript文件才能使用PhantomJS实现任何目标。

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

代码主要是从https://stackoverflow.com/a/12469284/4499924

复制的

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

答案 1 :(得分:0)

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


fs.write('output.html',pagehtml,'w');
相关问题