繁体   English   中英

使用 PhantomJS 保存远程图像

[英]Saving remote image with PhantomJS

我在没有Node 或 Casper 的 Ubuntu 上使用 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://stackoverflow.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);

});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM