viewportSize似乎不适用于PhantomJS

时间:2012-11-15 02:47:39

标签: viewport phantomjs

这个PhantomJS脚本的输出不应该是240x320像素吗?我得到一个大的默认大小的图像。 clipRect()似乎呈现正确大小的图像,但我需要页面的响应内容来反映实际的浏览器窗口大小。

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

page.viewportSize = { width: 240, height: 320 };  

page.open('http://cnn.com', function (status) {

    if (status !== 'success') {
        console.log('Unable to load the address!');
    } else {
        window.setTimeout(function () {
            page.render('default.png');
            phantom.exit();
        }, 200);
    }

});

4 个答案:

答案 0 :(得分:10)

这个有效!! 在issue的github页面上找到了片段。它强制'body'元素到页面viewportSize:

var width = 1024;
var height = 768;
var webpage = require('webpage');

page = webpage.create();
page.viewportSize = {width: width, height: height};
page.open('http://harness.io', function(status) {
    console.log(status);
    page.evaluate(function(w, h) {
      document.body.style.width = w + "px";
      document.body.style.height = h + "px";
    }, width, height);
    page.clipRect = {top: 0, left: 0, width: width, height: height};                                                                                                                           
    page.render('/tmp/test.png');
    phantom.exit();
});

答案 1 :(得分:5)

这是一个已知问题,但我找到了解决方法:

  1. 将页面加载到您喜欢的任何大小的iframe中。
  2. 渲染剪裁到iframe矩形的屏幕截图。
  3. 在此存储库中有代码可以执行:https://github.com/jbeuckm/Splasher

答案 2 :(得分:-1)

这似乎适用于1.9.7的Mac二进制文件:

page.set('viewportSize', {width: 320, height: 480});

答案 3 :(得分:-1)

在CasperJS 中,我处理了这个问题,使用了上面的方法,最后发现一旦我通过设置单个视口选项,这是不必要的(至少对于我来说,在CasperJS中) casper.viewport()方法。

我已在下面发布了我的版本,因此您可以看到它如何与多个网址一起使用。

// Requires node.js and casperjs (npm install casperjs)
var casper   = require('casper').create();
var root_dir = 'screenshots/';
var links    = [];
var root     = 'http://localhost:8001/';
var DEBUG    = false;
var opts     = {top: 0, left: 0, 'width': 1280, 'height': 1024};

function getHrefs() {
    // Taken wholesale from casperjs
    // http://docs.casperjs.org/en/latest/quickstart.html
    var links = document.querySelectorAll('.days li > a');
    return Array.prototype.map.call(links, function(e) {
        return e.getAttribute('href');
    });
}

function captureLinks(links) {
    casper.echo('= SCREEN CAPTURING LINKS ====');
    casper.each(links, function(self, link) {
        var filename = root_dir + link.replace('/index.html', '') + '.png';
        casper.echo('Capturing... ' + filename);

        // Relevant code...
        this.viewport(opts.width, opts.height);


        self.thenOpen(root + link, function() {
            // slight delay for external libraries and init loading
            this.wait(500, function(){
                this.capture(filename, opts);
            });
        });
    });
}

casper.start(root, function() {
    links = links.concat(this.evaluate(getHrefs));
    this.echo('= GETTING LINKS ====');
    if(DEBUG) this.echo(links.join('\n'));
    captureLinks(links);
});

casper.run();