2012-08-11 93 views

回答

50

要僅渲染頁面的一部分,您需要爲頁面設置clipRect屬性,然後渲染它。

var clipRect = document.querySelector(selector).getBoundingClientRect(); 
page.clipRect = { 
    top: clipRect.top, 
    left: clipRect.left, 
    width: clipRect.width, 
    height: clipRect.height 
}; 
page.render('capture.png'); 

我不明白你的問題的第二部分。 Phantom.js是無頭的意思,沒有用戶正在看的實際顯示。

+0

我明白phantom.js是無頭。我特別需要的是它能夠從瀏覽器視口中顯示的內容中捕獲網頁。你知道一個辦法嗎? – 2012-08-12 06:43:12

+0

好的,我明白你的意思。我不確定PhantomJS是否以這種方式工作。我不知道幻影是否有任何觀點或任何類似的概念。 – jasonlfunk 2012-08-13 00:34:00

+1

我明白了。我正在尋找某種類型的框架,它可以在Chrome擴展API中執行此操作或某些功能,使我可以執行此操作。如果您有任何指示,我將不勝感激。 – 2012-08-13 19:36:14

-5

我有同樣的需要,我想這和它爲我工作得很好:

不要忘記在URL

var page = require('webpage').create(); 
page.open('YourPageURL', function (status) { 

if (status !== 'success') { 
    console.log('Network Problem'); 
} else { 
    var p = page.evaluate(function() { 
     return document.getElementById('yourDivID').innerHTML 
    }); 
    console.log(p); 
} 
phantom.exit(); 
}); 
+2

投票下來,因爲這實際上並沒有像問題中所述的那樣將「個別HTML元素到PNG中」的屏幕截圖保存下來。它只是將一些元素的內部HTML打印到控制檯。 – 2013-06-05 10:42:06

5

您可以使用CasperJS的http://www,另一個項目基礎上PhantomJS。

casper.start('http://www.weather.com/', function() { 
    this.captureSelector('weather.png', '#wx-main'); 
}); 

casper.run(); 
21

工作示例。

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

page.open('http://google.com', function() { 
    // being the actual size of the headless browser 
    page.viewportSize = { width: 1440, height: 900 }; 

    var clipRect = page.evaluate(function(){ 
    return document.querySelector('#hplogo').getBoundingClientRect(); 
    }); 

    page.clipRect = { 
    top: clipRect.top, 
    left: clipRect.left, 
    width: clipRect.width, 
    height: clipRect.height 
    }; 

    page.render('google.png'); 
    phantom.exit(); 
}); 
0

下面的解決方案適用於我。

var clipRect = document.querySelector(selector).getBoundingClientRect(); 
    page.clipRect = { 
       top: clipRect.top, 
       left: clipRect.left, 
       width: clipRect.width, 
       height: clipRect.height 
     }; 
    page.render('capture.png'); 

但我注意到這隻適用於如果我們渲染圖像而不是pdf。 要爲PDF wokaround這個,試試這個

page.evaluate(function (element){ 
    $(element).appendTo('body'); 
    $('body > :not(' + element + ')').hide(); 
    }, element);  
    }); 

window.setTimeout(function(){ 
    page.render("page.pdf"); 
    },1000); 

這個鏈接可以幫助: How to hide all elements except one using jquery?

https://github.com/ariya/phantomjs/issues/10465