使用 PhantomJS 保存远程图像

Saving remote image with PhantomJS

我在 Ubuntu 没有 Node 或 Casper 上使用 PhantomJS 2.1.1。

fs.write('images/products/image.jpg', 'http://example.com/folder/someimage.jpg', 'w');

.. 尽管这会创建并非真正图像的 1xx 字节 jpeg 文件。有没有办法用 PhantomJS 下载任何类型的(JPEG、JPG、PNG)文件?

我最终这样做了:

$stdout = shell_exec("phantomjs ./scrape-images.js '".$url);
$images = isset($stdout) ? explode(',', $stdout) : '';

.. 然后:

$command = 'wget '.urlencode($image).' --output-document="/path/to/image/directory/'.$filename.'" --quiet --background >/dev/null 2>&1';
shell_exec($command);

编辑:唯一的缺点是某些网站检测到 wget 并抛出 404(即使我通过了用户代理和引用者)不是 真正的 用户,而 Phantom 会逃脱它。

更简单的方法,PhantomJS 自己保存图像:

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

page.viewportSize = { width: 1280, height: 800 };
page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36';

var url = "http://whosebug.com";
var selector = "#hlogo a";

page.open(url, function(){

    setTimeout(function(){

        var clipRect = page.evaluate(function (selector) { 
            return document.querySelector(selector).getBoundingClientRect(); 
        }, selector);

        page.clipRect = {
            top:    clipRect.top,
            left:   clipRect.left,
            width:  clipRect.width,
            height: clipRect.height
        };

        page.render('image.jpg');

        phantom.exit();

    }, 1000);

});