2017-04-14 91 views
2

目前無頭Chrome的問題是沒有API來渲染整個頁面,只有你在CLI參數中設置的「窗口」。無頭Chrome渲染整頁

我現在用的是chrome-remote-interface模塊,這是捕獲例如:

const fs = require('fs'); 
const CDP = require('chrome-remote-interface'); 

CDP({ port: 9222 }, client => { 

    // extract domains 
    const {Network, Page} = client; 

    Page.loadEventFired(() => { 
     const startTime = Date.now(); 
     setTimeout(() => { 
      Page.captureScreenshot() 
      .then(v => { 
       let filename = `screenshot-${Date.now()}`; 
       fs.writeFileSync(filename + '.png', v.data, 'base64'); 
       console.log(`Image saved as ${filename}.png`); 
       let imageEnd = Date.now(); 
       console.log('image success in: ' + (+imageEnd - +startTime) + "ms"); 
       client.close(); 
      }); 
     }, 5e3); 

    }); 
    // enable events then start! 
    Promise.all([ 
     // Network.enable(), 
     Page.enable() 
    ]).then(() => { 
     return Page.navigate({url: 'https://google.com'}); 
    }).catch((err) => { 
     console.error(`ERROR: ${err.message}`); 
     client.close(); 
    }); 
}).on('error', (err) => { 
    console.error('Cannot connect to remote endpoint:', err); 
}); 

爲了呈現完整的網頁,一個慢和黑客的解決辦法是局部呈現。設置固定高度並滾動瀏覽頁面,並在每X像素後截取屏幕截圖。問題是如何驅動滾動部分?注入自定義JS還是可以通過Chrome遠程接口實現?

回答

0

你見過這個嗎?

https://medium.com/@dschnr/using-headless-chrome-as-an-automated-screenshot-tool-4b07dffba79a

此位聲音的像它會幫助您解決問題:

// Wait for page load event to take screenshot 
    Page.loadEventFired(async() => { 
    // If the `full` CLI option was passed, we need to measure the height of 
    // the rendered page and use Emulation.setVisibleSize 
    if (fullPage) { 
     const {root: {nodeId: documentNodeId}} = await DOM.getDocument(); 
     const {nodeId: bodyNodeId} = await DOM.querySelector({ 
     selector: 'body', 
     nodeId: documentNodeId, 
     }); 
     const {model: {height}} = await DOM.getBoxModel({nodeId: bodyNodeId}); 

     await Emulation.setVisibleSize({width: viewportWidth, height: height}); 
     // This forceViewport call ensures that content outside the viewport is 
     // rendered, otherwise it shows up as grey. Possibly a bug? 
     await Emulation.forceViewport({x: 0, y: 0, scale: 1}); 
    } 

    setTimeout(async function() { 
     const screenshot = await Page.captureScreenshot({format}); 
     const buffer = new Buffer(screenshot.data, 'base64'); 
     file.writeFile('output.png', buffer, 'base64', function(err) { 
     if (err) { 
      console.error(err); 
     } else { 
      console.log('Screenshot saved'); 
     } 
     client.close(); 
     }); 
    }, delay); 
    }); 
+0

這是一個好的開始,但延遲加載的圖像將顯示其佔位符 – Drakes