如何在Phantomjs(javascript)中获取完整html页面的高度?

时间:2015-07-06 12:13:20

标签: javascript phantomjs viewport

您已经尝试了所有这些:

document.body.scrollHeight
document.body.offsetHeight
document.documentElement.clientHeight
document.documentElement.scrollHeight
document.documentElement.offsetHeight

这些工作在普通浏览器中但在Phantomjs中我得到了CMD(命令行窗口)高度..我想得到高度,以便我可以在代码中稍后裁剪屏幕截图..和页面的高度必须是在普通浏览器上查看

我得到300像素,我希望得到完整的html页面高度(根据网址而有所不同)..

1 个答案:

答案 0 :(得分:7)

这些值与其他浏览器一样提供预期值。完整的例子:

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

var url = 'http://www.stackoverflow.com/';

page.open(url, function(){
    console.log(page.evaluate(function(){
        return JSON.stringify({
            "document.body.scrollHeight": document.body.scrollHeight,
            "document.body.offsetHeight": document.body.offsetHeight,
            "document.documentElement.clientHeight": document.documentElement.clientHeight,
            "document.documentElement.scrollHeight": document.documentElement.scrollHeight
        }, undefined, 4);
    }));
    phantom.exit();
});

输出:

{
    "document.body.scrollHeight": 8777,
    "document.body.offsetHeight": 8777,
    "document.documentElement.clientHeight": 300,
    "document.documentElement.scrollHeight": 8777
}

原因可能不是您的情况:

  • 只能通过page.evaluate()访问DOM。在document之外存在page.evaluate()个对象,但它只是一个虚拟对象。
  • PhantomJS的默认视口为400x300像素。如果网页是响应式的,那么它只会使用此大小。
  • 与上述点一起,<body>可能不是可滚动的,而只是一些具有所有(可滚动)内容的子元素。在这种情况下,每个值都等于视口高度。
相关问题