如何使用 Python 和 Selenium 獲取頁面完整截圖?
我們可以使用 Selenium 獲取頁面的完整截圖。在執行任何測試用例時,我們可能會遇到失敗的情況。為了跟蹤這些失敗,我們會捕獲出現錯誤的網頁的截圖。
在測試用例中,可能由於以下原因導致失敗:
- 斷言未透過。
- 我們的應用程式和 Selenium 之間存在同步問題。
- 存在超時問題。
- 中間出現警報。
- 無法使用定位器識別元素。
- 實際結果與最終結果不匹配。
為了捕獲截圖,可以使用 `save_screenshot()` 方法。此方法可以獲取整個頁面的截圖。
語法
driver.save_screenshot("screenshot_t.png")
在引數中,我們必須提供截圖檔名以及 .png 副檔名。如果使用其他副檔名,則會丟擲警告訊息,並且無法檢視影像。
截圖將儲存在程式的同一路徑中。
示例
獲取全頁面截圖的程式碼實現。
from selenium import webdriver #browser exposes an executable file #Through Selenium test we will invoke the executable file which will then #invoke actual browser driver = webdriver.Chrome(executable_path="C:\chromedriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://tutorialspoint.tw/index.htm") #to refresh the browser driver.refresh() #to get the screenshot of complete page driver.save_screenshot("screenshot_tutorialspoint.png") #to close the browser driver.close()
廣告