【问题标题】:Capture screen shot of lazy loaded page with Node.js使用 Node.js 捕获延迟加载页面的屏幕截图
【发布时间】:2015-11-19 12:18:16
【问题描述】:

我正在寻找一种方法来在每次更改时截取长网页的屏幕截图。我想为此使用 Node.js。我的问题是关于如何用图像呈现整个页面并将其保存到磁盘和图像文件。

网页上的大多数图片都是延迟加载的。所以我想我需要先向下滚动整个页面,然后再进行屏幕截图。

我尝试了不同的工具:

  • casperjs
  • node-webshot
  • phantomjs

所有这些似乎都太复杂了,如果不是不可能的话,甚至无法安装。我没有成功。

casperjs 似乎是一个非常不错的选择,但我无法让它在 node.js 中工作。它一直在抱怨,casper.start() 不是一个有效的方法......

我与 node-webshot 最接近,但我没有设法向下滚动页面。

这是我目前的代码:

var webshot = require('webshot');

var options = {
    shotSize: {
        height: 'all',
        streamType: 'jpg'
    }
};

webshot('www.xx.com', 'xx.com.jpg', options, function(err) {
    // screen shot saved to 'xx.com.jpg'
});

顺便说一句,我正在 Mac 上开发。完成的 Node 应用程序将位于 linux 服务器上。

感谢任何cmets或经验!

【问题讨论】:

  • CasperJS 在 PhantomJS 内部运行,而 PhantomJS 又具有与 node.js 不同的执行环境。您不能直接在节点中运行 PhantomJS/CasperJS 脚本。您要么需要 (1) 通过 child_process 执行 CasperJS 进程,要么 (2) 使用像 Spooky.js 这样的库(注意三种不同的上下文)。

标签: javascript node.js phantomjs casperjs


【解决方案1】:

对于安装 CasperJS 并没有什么帮助,因为在 Windows 上它只需使用 npm install casperjs -g 即可工作。

我已经建立了一个简单的脚本来做截图:

var casper = require('casper').create();
casper.options.viewportSize = {width: 1600, height: 950};
var wait_duration = 5000;
var url = 'http://stackoverflow.com/questions/33803790/capture-screen-shot-of-lazy-loaded-page-with-node-js';
console.log("Starting");
casper.start(url, function() {
    this.echo("Page loaded");
});

casper.then(function() {
    this.scrollToBottom();
    casper.wait(wait_duration, function() {
        casper.capture('screen.jpg');
        this.echo("Screen captured");
    });
});

casper.then(function() {
    this.echo("Exiting");
    this.exit();
});

casper.run();

代码相当简单:

  • 加载网址
  • 滚动到底部
  • 等待特定持续时间 (wait_duration) 以加载内容
  • 截屏
  • 结束

希望这对你有用!

【讨论】:

    【解决方案2】:

    此代码适用于我在 OSX 中的节点,将其保存为 test.js 并在 CLI 中运行节点 test.js

    var webshot = require('webshot');
    
    var options = {
      streamType: 'png',
      windowSize: {
      width: 1024,
      height: 768
    },
      shotSize: {
        width: 'all',
        height: 'all'
      }
    };
    
    webshot("blablabla.com","bla-image.png",options,(err) => {
      if(err){
        return console.log(err);
      }
      console.log('image succesfully');
    });
    

    【讨论】:

      【解决方案3】:

      您可以通过 Selenium 自动化它,http://webdriver.io/。是的,它最像一个测试引擎,而不是屏幕截图应用程序,但您可以完全控制浏览器自动化并在调试时在显示器上看到浏览器

      • 启动 selenium 服务器,例如 Google Chrome
      • 加载您的页面
      • 使用 webdriver.io 进行滚动、点击等一切操作
      • 觉得合适的时候拍张照片
      • 关闭会话

      使用 nodejs 安装 selenium 的快速方法 -> https://github.com/vvo/selenium-standalone

      【讨论】:

      • 我有一个使用 firefox xulrunner 应用程序的工作示例,但它比其他所有解决方案都复杂
      猜你喜欢
      • 2019-06-18
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-06
      • 1970-01-01
      相关资源
      最近更新 更多