2017-02-20 64 views
0

我正在尝试使用下面的代码截取网页截图。稍做修改,我可以将截图保存为PNG。但是,噩梦.JS文档指出.screenshot()方法将返回“图像数据的缓冲区”。如果没有提供“路径”选项。获取Nightmare.JS(v 2.9.1)截图缓冲区

截图完成执行后,如何才能访问缓冲区?

const getScreenshot = (url) => { 
    nightmare 
    .goto(url) 
    .wait() 
    .evaluate(() => { 
     const body = document.querySelector('body'); 

     return { 
      height: body.scrollHeight, 
      width: body.scrollWidth 
     }; 
    }) 
    .then(function(dimensions) { 
     return nightmare 
     .viewport(dimensions.width, dimensions.height) 
     .wait(1000) 
     // .screenshot(require('path').join(__dirname, 'screenshot.png')) 
     .screenshot() 
    }) 
    .then(function(e) { 
     console.log('nightmare', nightmare) 
     nightmare.end() 
      .then(function(result) { 
      console.log('completed screenshot', result) 
      console.log('done'); 
     }) 
    }); 
} 

回答

1

您是几乎有:在您的最终.then()e应为PNG完成的缓冲区。要验证,您可以稍微更改.then()功能:

function(e) { 
     //this should print "e is a buffer: true" 
     console.log(`e is a buffer: ${Buffer.isBuffer(e)}`); 

     return nightmare.end() 
     .then(function(result) { 
      console.log('completed screenshot', result) 
      console.log('done'); 
     }); 
    } 
+0

非常好!谢谢Ross – bresson

+0

没问题,高兴帮忙:) – Ross