如何在Selenium和Python中獲取頁面中特定元素的截圖?


我們可以獲取Selenium頁面中特定元素的截圖。在執行任何測試用例時,我們可能會遇到特定元素的失敗。為了查明特定元素的失敗原因,我們會嘗試捕獲錯誤所在的截圖。

元素錯誤可能由以下原因造成:

  • 斷言未透過。
  • 應用程式和Selenium之間存在同步問題。
  • 存在超時問題。
  • 中途出現警報。
  • 無法使用定位器識別元素。
  • 實際結果和最終結果不匹配。

要捕獲截圖,可以使用`save_screenshot()`方法。此方法會捕獲整個頁面的截圖。

沒有內建方法可以捕獲單個元素的截圖。為此,我們必須將全頁面截圖裁剪到特定元素的大小。

語法

driver.save_screenshot('screenshot_t.png')

在引數中,我們必須提供截圖檔名以及`.png`副檔名。如果使用其他副檔名,則會丟擲警告訊息,並且無法檢視影像。

截圖將儲存在程式的同一路徑下。

這裡我們需要藉助Webdriver中的`location`和`size`方法來裁剪影像。為此,我們需要匯入PIL影像庫。它可能包含在標準庫中,也可能不包含。如果不可用,可以使用`pip install Pillow`命令安裝。

每個元素都有一個唯一的(x, y)座標位置。`location`方法給出元素的x和y座標。

每個元素都有一個由高度和寬度定義的尺寸。這些值透過`size`方法獲得,該方法給出元素的高度和寬度。

現在開始裁剪影像。

# to get the axes
ax = location['x'];
ay = location['y'];
width = location['x']+size['width'];
height = location['y']+size['height'];
# to compute the cropped image dimension
cropImage = Image.open('screenshot_t.png')
cropImage = cropImage.crop((int(ax), int(ay), int(width), int(height)))
cropImage.save('cropImage.png')

示例

捕獲特定元素截圖的程式碼實現。

from selenium import webdriver
from PIL import Image
#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()
# identifying the element to capture the screenshot
s= driver.find_element_by_xpath("//input[@class='gsc-input']")
# to get the element location
location = s.location
# to get the dimension the element
size = s.size
#to get the screenshot of complete page
driver.save_screenshot("screenshot_tutorialspoint.png")
#to get the x axis
x = location['x']
#to get the y axis
y = location['y']
# to get the length the element
height = location['y']+size['height']
# to get the width the element
width = location['x']+size['width']
# to open the captured image
imgOpen = Image.open("screenshot_tutorialspoint.png")
# to crop the captured image to size of that element
imgOpen = imgOpen.crop((int(x), int(y), int(width), int(height)))
# to save the cropped image
imgOpen.save("screenshot_tutorialspoint.png")
#to close the browser
driver.close()

更新於:2020年7月29日

2K+ 瀏覽量

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告