如何使用 phantomjs 通过动态数据可视化拍摄屏幕截图

How to use phantomjs to take screen shot with dynamic data visualization

本文关键字:可视化 屏幕截图 数据 动态 何使用 phantomjs      更新时间:2023-09-26

当我按照本教程(http://phantomjs.org/screen-capture.html)进行屏幕捕获时,我遇到了一些关于动态数据可视化的问题。

在该教程中,它使用了一些代码,例如:

var page = require('webpage').create();
page.open('http://localhost:8080/index.html', function() {
  page.render('screenshot.png');
  phantom.exit();
});

但这似乎仅适用于静态页面。我想知道我是否有一些用户交互并使该页面更改(如鼠标单击更改颜色等),如何捕获显示当前屏幕

如果 phantomjs 不能以这种方式工作,任何人都可以提出其他解决方案吗?

当然,只需在page.open()之后和page.render()之前添加您想要的功能。

page.open('http://localhost:8080/index.html', function() {
  /**
   * Add your events and actions here...
   * or call JS functions of the page itself...
   */
  page.evaluate(function() {
    /**
     * Inject a <style text/css> tag in the head,
     * which set the bgcolor
     */  
      var style = document.createElement('style'),
      text = document.createTextNode('body { background: red }');
      style.setAttribute('type', 'text/css');
      style.appendChild(text);
      document.head.insertBefore(style, document.head.firstChild);
  });
  page.render('screenshot.png');
  phantom.exit();
});

请记住,您在这里使用的是Javascript,并且可以注入任意帮助程序脚本,如CasperJS或jQuery,并在加载的页面上使用它们的功能。

对于灵感:

  • PhantomJS;单击一个元素
  • 如何使用PhantomJS或其他工具检索加载需要鼠标单击的ajax数据
    • 特别是这个点击,点击后截图和Ajax东西的答案:https://stackoverflow.com/a/18274644/1163786
  • 浏览一下,然后截图:https://stackoverflow.com/a/17506213/1163786