12

这个 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

4 回答 4

11

这行得通!在问题的 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();
});
于 2014-10-01T14:45:01.447 回答
5

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

  1. 将页面加载到您喜欢的任何大小的 iframe 中。
  2. 渲染剪裁到 iframe 矩形的屏幕截图。

在这个存储库中有代码可以做到这一点:https ://github.com/jbeuckm/Splasher

于 2013-05-25T04:24:53.003 回答
-1

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

page.set('viewportSize', {width: 320, height: 480});
于 2014-08-17T21:55:56.213 回答
-1

在 CasperJScasper.viewport()中,我处理了这个问题,使用了上述方法,最终发现一旦我通过该方法设置了单个视口选项,就没有必要(至少对我来说,在 CasperJS 中) 。

我已经在下面发布了我的版本,因此您可以看到它如何同时处理多个 url。

// 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();
于 2014-10-05T23:56:27.293 回答