2017-02-20 91 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