【问题标题】:Take screenshot of webelement in Selenium Python and save file在 Selenium Python 中截取 webelement 的屏幕截图并保存文件
【发布时间】:2026-02-01 06:05:02
【问题描述】:

我正在尝试根据类名截取特定网页元素的屏幕截图。我已经按照How to take screenshot with Selenium WebDriverHow to screenshot a specified WebElement in Selenium using PythonHow to take partial screenshot with Selenium WebDriver in python?中描述的方法进行了

以下是命令及其错误:

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 此命令执行,但 image 对象作为绑定方法出现,如下面引用的文本所示

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

如何将此绑定方法保存到磁盘上的图像?为什么命令不执行?使用 Python 3.8,如果这很重要。

【问题讨论】:

  • driver_instance.save_screenshot('file_name') 将截取整个网页,而不是特定的 WebElement,这是问题的目标

标签: python selenium screenshot webpage-screenshot


【解决方案1】:

我认为你使用的是 firefox 而不是 chrome 我找到了解决办法

from selenium import webdriver
from PIL import Image

fox = webdriver.Firefox()
fox.get('https://*.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://*.com/a/37565356/8951071

【讨论】:

  • 虽然这个解决方案确实解决了当前的问题,但它仍然没有教一种更优雅的方法来使用 Selenium 库保存 WebElements 的屏幕截图,这种方法可以用于许多其他情况。已投票但未标记为答案。非常感谢@Ahmed