22

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

4

5 回答 5

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');

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

于 2012-08-11T19:43:40.700 回答
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();
});
于 2015-07-10T10:29:02.493 回答
5

您可以使用基于 PhantomJS 的另一个项目 CasperJS。

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

casper.run();
于 2014-05-08T14:24:31.327 回答
0

下面的解决方案对我有用。

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

但我注意到,只有在我们渲染图像而不是 pdf 时,这才有效。要为 pdf 解决这个问题,试试这个

page.evaluate(function (element){
    $(element).appendTo('body');
    $('body > :not(' + element + ')').hide(); 
   }, element);       
  });

window.setTimeout(function(){
    page.render("page.pdf");
  },1000);

此链接可能会有所帮助: 如何隐藏除使用 jquery 的元素之外的所有元素?

https://github.com/ariya/phantomjs/issues/10465

于 2016-04-27T13:04:55.487 回答
-5

我有同样的需求,我试过了,对我来说效果很好:

不要忘记http://www网址中的

var page = require('webpage').create();
page.open('YourPageURL', function (status) {

if (status !== 'success') {
    console.log('Network Problem');
} else {
    var p = page.evaluate(function () {
        return document.getElementById('yourDivID').innerHTML
    });
    console.log(p);
}
phantom.exit();
});
于 2013-03-19T21:53:20.443 回答