如何使用PhantomJS渲染页面的一部分?

Dan*_*maa 22 javascript phantomjs

我想使用Phantom.JS将各个HTML元素渲染到PNG中.有谁知道这是否可能?另外,我如何使用Phantom.js呈现用户已经在查看的页面?

jas*_*unk 50

要仅渲染页面的一部分,您需要为页面设置clipRect属性,然后再渲染它.

var clipRect = document.querySelector(selector).getBoundingClientRect();
page.clipRect = {
    top:    clipRect.top,
    left:   clipRect.left,
    width:  clipRect.width,
    height: clipRect.height
};
page.render('capture.png');
Run Code Online (Sandbox Code Playgroud)

我不明白你问题的第二部分.Phantom.js无头,意味着没有用户正在看的实际显示.

  • 上面的例子需要`var clipRect = page.evaluate(function(){return document.querySelector("#someid").getBoundingClientRect();});`当我试过的时候.evaluate函数在页面上下文中评估文档. (25认同)

小智 22

工作实例.

var page = require('webpage').create();

page.open('http://google.com', function() {
  // being the actual size of the headless browser
  page.viewportSize = { width: 1440, height: 900 };

  var clipRect = page.evaluate(function(){
    return document.querySelector('#hplogo').getBoundingClientRect();
  });

  page.clipRect = {
    top:    clipRect.top,
    left:   clipRect.left,
    width:  clipRect.width,
    height: clipRect.height
  };

  page.render('google.png');
  phantom.exit();
});
Run Code Online (Sandbox Code Playgroud)


Sil*_*ior 5

您可以使用CasperJS,这是另一个基于PhantomJS的项目.

casper.start('http://www.weather.com/', function() {
    this.captureSelector('weather.png', '#wx-main');
});

casper.run();
Run Code Online (Sandbox Code Playgroud)