在带有覆盖的页面上使用phantomjs捕获屏幕截图

Capture screenshot with phantomjs on a page with overlay

本文关键字:phantomjs 屏幕截图 覆盖      更新时间:2023-09-26

我正试图将网站的一个特定div捕获到屏幕截图中,以方便我必须做的一些繁重的工作。到目前为止,我正在使用我在这个完全相同的网站上找到的代码,这有点工作:

var page = require('webpage').create();
page.open('http://www.example.org', function() {
  // being the actual size of the headless browser
  page.viewportSize = { width: 1440, height: 900 };
  var clipRect = page.evaluate(function(){
    return document.querySelector("div.example").getBoundingClientRect();
  });
  page.clipRect = {
    top:    clipRect.top,
    left:   clipRect.left,
    width:  clipRect.width,
    height: clipRect.height
  };
  page.render('google.png');
  phantom.exit();
});

这确实有效,但我有两个问题:

1) 该页面在第一次访问时有一个覆盖,屏幕截图上出现了一个弹出式窗口。2) 图像显然是在需要渲染时下载的(它们只在网页上滚动时出现)

所以最后我得出这样的结论:问题

我没有使用phantomjs的经验,所以我不知道如何解决这个问题。消除覆盖DIV和以某种方式迫使图像在截图前加载可能会起作用,但我不知道如何实际编码。

非常感谢!

您可以通过编程删除覆盖元素,以像素为单位设置页面滚动位置,等待几秒钟加载图像,然后进行屏幕截图。

var page = require('webpage').create();
page.viewportSize = { width: 1440, height: 900 };
page.open('http://www.jovago.com', function() {
    // jQuery is used at the target site
    page.evaluate(function(){
        $("#overlay, #modal").remove();
    });
    // Simulate scrolling down
    page.scrollPosition = {
        top: 1400,
        left: 0
    };    
    var clipRect = page.evaluate(function(){
        return document.querySelector("div.top-destinations-homepage.promo-banners-box").getBoundingClientRect();
    });
    page.clipRect = {
        top:    clipRect.top,
        left:   clipRect.left,
        width:  clipRect.width,
        height: clipRect.height
    };
    // Wait 10 seconds for images to download
    setTimeout(function(){
          page.render('jovago.png');
          phantom.exit();
    }, 10000);
});