簡體   English   中英

在 Selenium Python 中截取 webelement 的屏幕截圖並保存文件

[英]Take screenshot of webelement in Selenium Python and save file

我正在嘗試根據類名截取特定網頁元素的屏幕截圖。 我遵循了如何使用 Selenium WebDriver 截屏如何使用 Python 在 Selenium 中截取指定的 WebElement以及如何在 python 中使用 Selenium WebDriver 截取部分屏幕中描述的方法?

以下是命令及其錯誤:

driver.find_element_by_class_name("views-field-body").screenshot("test.png")driver.find_element_by_class_name("views-field-body").screenshot_as_png

兩次我都收到錯誤消息

selenium.common.exceptions.WebDriverException:消息:未知命令:session/75c3765173a9cf726d35afa7978d9b6e/element/0.5926184656216698-3/screenshot

當我嘗試image = driver.find_element_by_class_name("views-field-body").screenshot這個命令執行時,但圖像對象作為綁定方法出現,如下面引用的文本所示

selenium.webdriver.remote.webelement.WebElement 的綁定方法 WebElement.screenshot (session="75c3765173a9cf726d35afa7978d9b6e", element="0.5926184656216698-3")

如何將這種綁定方法保存到磁盤上的圖像? 為什么命令沒有執行? 如果重要的話,使用 Python 3.8。

我認為您使用的是 Firefox 而不是 chrome 我找到了解決方案

from selenium import webdriver
from PIL import Image

fox = webdriver.Firefox()
fox.get('https://stackoverflow.com/')

# now that we have the preliminary stuff out of the way time to get that image :D
element = fox.find_element_by_id('hlogo') # find part of the page you want image of
location = element.location
size = element.size
fox.save_screenshot('screenshot.png') # saves screenshot of entire page
fox.quit()

im = Image.open('screenshot.png') # uses PIL library to open image in memory

left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']


im = im.crop((left, top, right, bottom)) # defines crop points
im.save('screenshot.png') # saves new cropped image

https://stackoverflow.com/a/37565356/8951071

暫無
暫無

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

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