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

How to render part of a page with PhantomJS?

本文关键字:一部分 何使用 PhantomJS      更新时间:2023-09-26

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

要仅呈现页面的一部分,您需要为页面设置 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 是无头的,这意味着没有用户正在查看的实际显示。

工作示例。

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();
});

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

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

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

    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

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

不要忘记网址中的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();
});