2016-09-29 80 views
3

我使用phantomjs使用python拍攝網頁快照(例如:http://www.baixaki.com.br/)。如何使用python在phantomjs中創建部分網頁快照?

這裏是代碼:

from selenium import webdriver 
driver = webdriver.PhantomJS() # or add to your PATH 

driver.get('http://www.baixaki.com.br/') 
driver.save_screenshot('screen6.png') # save a screenshot to disk 

輸入是一個URL,則輸出是圖像。 問題是生成的快照很窄而且很長: narrow and long snapshot

我想僅捕獲適合頁面而不滾動和全寬的內容。 例如,像這樣: enter image description here

  • 我正在尋找一個通用的解決方案而不是具體的一個。

希望你在這裏的幫助。

+0

http://stackoverflow.com/questions/11917042/how-to-render-part-of-a-page-with-phantomjs – jinksPadlock

+0

這篇文章是不是在python中,並被定向到一個特定的網頁使用特定元素的ID。我正在尋找一個通用的解決方案,使用Python的快照在頁面的特定部分... –

+0

嗯...沒有我認爲這將是有用的,因爲Python比我預期的更加不同(認爲跳躍會更容易);你有沒有嘗試webdriver set_window_size函數?例如,driver.set_window_size(1400,1000) – jinksPadlock

回答

3

你可以嘗試裁剪圖像(我使用Python 3.5,所以你可能需要調整使用StringIO的,如果你在Python 2.X是):其中信貸是由於

from io import BytesIO 
from selenium import webdriver 
from PIL import Image 

if __name__ == '__main__': 
    driver = webdriver.PhantomJS('C:<Path to Phantomjs>') 
    driver.set_window_size(1400, 1000) 
    driver.get('http://www.baixaki.com.br/') 
    driver.save_screenshot('screen6.png') 
    screen = driver.get_screenshot_as_png() 

    # Crop image 
    box = (0, 0, 1366, 728) 
    im = Image.open(BytesIO(screen)) 
    region = im.crop(box) 
    region.save('screen7.png', 'PNG', optimize=True, quality=95) 

信用: https://gist.github.com/jsok/9502024

+0

謝謝。看起來很有希望。 –

+0

這將裁剪圖像的頂部,但在我的情況下,該頁面有一個彈出對話框,位於該瘋狂高度截圖的**中間**處,因此我必須裁剪兩次:一次用於頂部(獲取頁面標題),以及中間的一個(獲取中間的對話框)。我需要一種方法來讓selenium尊重set_window_size()的** height **。它想要screencap整個可滾動高度,而不是「查看矩形」。 –