Capture screenshot of an Element using Python Selenium WebDriver

The Blog To Learn Selenium and Test Automation

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.

location

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.

  1. location[‘x’] returns ‘x’ co-ordinate of the element
  2. location[‘y’] returns ‘y’ co-ordinate

size

Like location, each WebElement has width and height or size.

  1. size[‘width’] returns ‘width’ of the element
  2. 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.

 

3 Responses

  1. shyam maurya says:

    hey thanks buddy !

  2. […] Read articles for more details about taking screenshot and element screenshot […]

  3. Hamed says:

    Hi,
    Thank you for clear explanation. I tried to capture screenshot from CAPTCHA, but this code screens wrong and unrelated pixels were captured. I use xpath for finding place of CAPTCHA.

Leave a Reply

Your email address will not be published. Required fields are marked *