0

I am trying to take a screenshot of a particular webpage element based on class name. I have followed the methods described in How to take screenshot with Selenium WebDriver, How to screenshot a specified WebElement in Selenium using Python and How to take partial screenshot with Selenium WebDriver in python?

Following are the commands and their errors:

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

Both times I get the error message as

selenium.common.exceptions.WebDriverException: Message: unknown command: session/75c3765173a9cf726d35afa7978d9b6e/element/0.5926184656216698-3/screenshot

When I try image = driver.find_element_by_class_name("views-field-body").screenshot this commands executes, but the image object comes out as bound method as shown in the quoted text below

bound method WebElement.screenshot of selenium.webdriver.remote.webelement.WebElement (session="75c3765173a9cf726d35afa7978d9b6e", element="0.5926184656216698-3")

How does one save this bound method to image on disk? Why are the commands not executing? Using Python 3.8, if that matters.

solyarist
  • 424
  • 3
  • 17
  • _driver_instance.save_screenshot('file_name')_ would screenshot the full webpage, and not a particular WebElement, which is the objective of the question – solyarist Nov 28 '19 at 17:20

1 Answers1

2

I think you use firefox not chrome I found a solution

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

Ahmed Abdelazim
  • 717
  • 7
  • 14
  • While this solution does solve the current problem, it still does not teach a more elegant way of saving screenshots of WebElements using Selenium library, that could be used for many other situations. Upvoted but not marked as answer. Much thanks @Ahmed – solyarist Nov 28 '19 at 17:29