【问题标题】:Get javascript rendered html source using phantomjs使用 phantomjs 获取 javascript 呈现的 html 源
【发布时间】:2020-10-17 23:29:27
【问题描述】:

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

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

我不知道使用 phantomjs。我在shell脚本方面有一点经验。所以我尝试用curl 来做到这一点。但由于 curl 不足以呈现 javascript,我只能获取默认源代码的 html。未下载渲染的内容。我听说 ruby​​ mechanize 可以完成这项工作。但我对红宝石一无所知。所以在进一步调查中,我发现了命令行工具phantomjs。我如何使用phantomjs 做到这一点?

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

【问题讨论】:

  • 分享您的研究对每个人都有帮助。告诉我们您尝试了什么以及为什么它不能满足您的需求。这表明您已经花时间尝试帮助自己,它使我们免于重复明显的答案,最重要的是它可以帮助您获得更具体和相关的答案!另见how to ask
  • 我已经根据我所做的研究更新了我的问题。
  • 您是仅使用 phantomjs 来下载 html 内容还是尝试将其下载为图像?用于生成图像检查phantomjs.org/screen-capture.html
  • 我只是想获取一个页面的html内容。

标签: javascript html shell phantomjs


【解决方案1】:

不幸的是,仅使用 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

【讨论】:

  • 我希望这能回答我的问题。我想我可能需要使用在我的目标应用程序中加载的脚本而不是这个。
  • 我想这适用于这个特定的实例,但我给你的解决方案适用于任何页面
  • 根据我的经验,您还需要添加一个时间延迟,以便通过将主体包裹在 page.open 内并使用 setTimeout(function() { <BODY> }, delay); (例如,delay = 5000 毫秒)来完全呈现页面。您可以使用system.ags[2] 将延迟设置为可选参数,您可以使用system.args.length 检查参数长度。
【解决方案2】:
var pagehtml = page.evaluate("function() {"+ 
  "return '<html><head>' + document.head.innerHTML + '</head>' + '<body>' + document.body.innerHTML + '</body></html>';" + 
"}");


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

【讨论】:

    猜你喜欢
    • 2019-11-28
    • 2014-11-02
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    • 2012-05-17
    • 2013-12-09
    相关资源
    最近更新 更多