+91 9790664230
kumar.arun211@gmail.com

Capture screenshot of an Element using Python Selenium WebDriver

Blog to learn python selenium from java selenium

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')

 

One Response

  1. […] Capture screenshot of an Element using Python Selenium WebDriver – Selenium Blog on Taking Screenshot using Python Selenium WebDriver […]

Leave a Reply

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

© 2018 Copyrights. All Rights Reserved. Arunkumar Velusamy