Capture screenshot of an Element using Python Selenium WebDriver
In this post, we explored how to capture Screenshot in Python Selenium Webdriver.
Sometimes we may just want to
- capture a part of the page,
- just on specific element based on ID, or
- any specific element locator.
For example, we would like to capture the logo in Google page with id = “hplogo”
Selenium WebDriver has feature only to capture the whole page; And does not have screenshot function that takes element id or name as input.
Taking screenshot of an element is not straight forward in Selenium WebDriver.
To do this, we have to capture screenshot of page first, get dimension and size of the element, and then using image libraries crop the image as required.
Before proceeding screenshot, lets look at two methods available for WebDriver element object.
A web element has its own position on page and generally it is measured in x and y pixels and known as (x,y) co-ordinates of element. and location object contains these two values.
- location[‘x’] returns ‘x’ co-ordinate of the element
- location[‘y’] returns ‘y’ co-ordinate
Like location, each WebElement has width and height or size.
- size[‘width’] returns ‘width’ of the element
- size[‘height’] returns ‘height’ of the element
Using x,y co-ordinates and width, height values we can crop the image and store.
from selenium import webdriver from PIL import Image driver = webdriver.Firefox(executable_path='[Browser Driver Path]') driver.get('https://www.google.co.in') element = driver.find_element_by_xpath("//div[@id='hplogo']") location = element.location size = element.size driver.save_screenshot("/data/image.png") x = location['x'] y = location['y'] width = location['x']+size['width'] height = location['y']+size['height'] im = Image.open('/data/WorkArea/image.png') im = im.crop((int(x), int(y), int(width), int(height))) im.save('/data/image.png')
Happy coding!! Please let us know your thoughts in comments.