如何使用phantomjs从站点下载图像

And*_*rle 7 coffeescript phantomjs

我想保存一些网站的图像.目前我可以获得图像的路径,但我不知道如何使用phantomJs获取和保存图像.

findRotationTeaserImages = ->
  paths = page.evaluate ->
    jQuery('.rotate img').map(-> return this.src).get()

  for path, i in paths
    console.log(path);
    //save the image
Run Code Online (Sandbox Code Playgroud)

Tom*_*Tom 18

我知道这是一个老问题,但你只需将每个图像的尺寸和位置存储在一个对象中,然后改变phantomjs page.clipRect,使page.render()方法只渲染其中的区域.图像是.这是一个示例,从http://dribbble.com/抓取多个图像:

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

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

    page.includeJs('//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js',function() {

        var images = page.evaluate(function() {
            var images = [];
            function getImgDimensions($i) {
                return {
                    top : $i.offset().top,
                    left : $i.offset().left,
                    width : $i.width(),
                    height : $i.height()
                }
            }
            $('.dribbble-img img').each(function() {
                var img = getImgDimensions($(this));
                images.push(img);
            });

            return images;
        });

        images.forEach(function(imageObj, index, array){
            page.clipRect = imageObj;
            page.render('images/'+index+'.png')
        });

        phantom.exit();
    });
});
Run Code Online (Sandbox Code Playgroud)


小智 9

现在有另一种方法可以做到这一点.

var fs = require("fs");
var imageBase64 = page.evaluate(function(){
  var canvas = document.createElement("canvas");
  canvas.width =img.width;
  canvas.height =img.height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0);      
  return canvas.toDataURL ("image/png").split(",")[1];
})
fs.write("file.png",atob(imageBase64),'wb');
Run Code Online (Sandbox Code Playgroud)


And*_*rle 5

通过启动运行下载映像的节点脚本的子进程来解决此问题:

幻影剧本:

findRotationTeaserImages = ->
  paths = page.evaluate ->
    jQuery('.rotate img').map(-> return this.src).get()

  args = ('loadRotationTeaser.js ' + paths.join(' ')).split(' ')

  child_process.execFile("node", args, null, (err, stdout, stderr) ->
    phantom.exit()
  )
Run Code Online (Sandbox Code Playgroud)

nodeJs脚本

http = require('http-get');

args = process.argv.splice(2)

for path, i in args
  http.get path, 'public/images/rotationTeaser/img' + i + '.jpeg', (error, result) ->
Run Code Online (Sandbox Code Playgroud)