簡體   English   中英

使用 Chrome 驅動程序使用 Selenium Python 截取完整的 web 頁面

[英]Take screenshot of full web page with Selenium Python with Chrome driver

我想截取一個網站的整個頁面。 以下是網站條件

  1. 它需要使用登錄表單進行身份驗證
  2. 我要截圖的網站是Javascript渲染的(動態渲染),不是static渲染的( body標簽里面就是script標簽)

我確實嘗試了一些我能找到的解決方案,但它們都沒有按我的意願工作。 以下是我嘗試過的一些嘗試

  1. 鏈接這個需要使用 headless chrome,這讓我無法填寫登錄表格
  2. 當我嘗試刪除無頭選項時,我收到此錯誤"message":"Cannot take screenshot with 0 height." 我猜這是因為內容是由 Javascript 渲染的。 請注意,我已經給了它一些時間來渲染time.sleep(5)
  3. 當我嘗試選擇另一個元素時,結果會有所不同。 有些給出了與上面相同的錯誤消息,有些給出了屏幕截圖但不是整頁,只是可見部分(與使用browser.save_screenshot()的結果相同)。 下面是我試過的代碼。

 def S(X): return browser.execute_script( 'return document.querySelector("#main-layout-content").scroll'+X ) browser = webdriver.Chrome() browser.get('some link go here') browser.set_window_size(S('Width') + 100, S('Height') + 1000) #The print statement below work print(S('Height')) browser.find_element_by_id('main-layout-content').screenshot('web_screenshot.png')

有什么辦法可以達到我的需要嗎?

這是我為獲取網頁的全尺寸屏幕截圖所做的

from selenium import webdriver
browser = webdriver.Chrome()

# We go to the webpage here and wait 2 seconds for fully load
browser.get('https://someURL')
time.sleep(2)

# Where to save the picture
directory = '/home'
# Video title
title = 'Hello world'

try:
        # We try to get the top-level component in which all out page is its children
        # This is different for each website
        elem = browser.find_element_by_id('main-layout-content')
        # Get the height of the element, and adding some height just to be sage
        total_height = elem.size['height'] + 1000
        # Set the window size - what is the size of our screenshot
        # The width is hardcoded because the screensize is fixed for each computer
        browser.set_window_size(1920, total_height)
        # Wait for 2 seconds
        time.sleep(2)
        # Take the screenshot
        browser.find_element_by_id(
            'main-layout-content').screenshot(f'./{directory}/{title}.png')
except SystemError as err:
        print('Take screenshot error at' + title)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM