PhantomJS:获取页面的呈现尺寸

PhantomJS: getting the rendered dimensions of a page

本文关键字:获取 PhantomJS      更新时间:2023-09-26

当使用PhantomJS进行屏幕捕获时,其中大部分页面内容都是在通过JavaScript加载时或加载期间添加的,我遇到了问题。 调用 render() 会生成正确的图像,显示页面的完整内容,但评估 document.body.clientHeight 会返回一个很小的值,该值可能是添加任何内容之前的页面高度。

如何在 PhantomJS 渲染图像时获取图像的高度/宽度? 我不认为这是一个时间问题,我尝试交换事物的顺序或设置长时间的延迟以确保所有内容都完全加载。

var wp = require('webpage');
var page = wp.create();
page.viewportSize = { width: 1024, height: 768};
page.open(url, function (status) {
    if (status === 'success') {
        var f = "rendered.png";
        //Produces an image with height 4073px
        page.render(f);
        //height is only 150
        var height = page.evaluate(function() { return document.body.offsetHeight }),
            width = page.evaluate(function() { return document.body.offsetWidth });
            console.log(height,width);
    }
});

尝试使用 page.onLoadFinished 回调:

var wp = require('webpage');
var page = wp.create();
page.viewportSize = { width: 1024, height: 768};
page.open(url);
page.onLoadFinished = function() {
    var f = "rendered.png";
    //Produces an image with height 4073px
    page.render(f);
    //height is only 150
    var height = page.evaluate(function() { return document.body.offsetHeight }),
        width = page.evaluate(function() { return document.body.offsetWidth });
    console.log(height,width);
};

这应该在页面内容完成加载后返回正确的高度和宽度。我认为不同之处在于page.onLoadFinished等待所有内容完成加载,而不仅仅是等同于success状态的200 OK响应。