Thursday, July 21, 2011

Getting the width and height of an Image using Selenium

People has kept asking me how to capture the width and height of an image/element using selenium. I tried to get an answer to it and the solution is very simple. The solution comes with Selenium itself.

Selenium-1 consists of certain functions for storing element values like getElementHeight, getElementWidth, getElementPositionLeft, getElementPositionRight, getElementPositionTop.

Similarly in Selenium-2(WebDriver) you can use the getSize() function which will return a "Dimension" class object. You can then use the getHeight() and getWidth() functions over it for getting the width and height of the element.


We can use these functions to get the position of the element and also its width and height.
Following is an example for getting the height and width of an image/element on the browser using Selenium-1.


height = selenium.getElementHeight("locaton to the image on the browser.(xpath or id)")
width = selenium.getElementWidth("location to the image on the browser.(xpath or id)")

Following is an example for getting the height and width of an image/element on the browser using Selenium-2(WebDriver).

height = driver.findElement("location to the image on the browser.(xpath or id)").getSize().getHeight();
width = driver.findElement("location to the image on the browser.(xpath or id)").getSize().getWidth()


2 comments :

Ahhlecks said...

how would that work in Selenium 2 using WebDriver?

Varun Menon said...

@Ahhlecks - Updated the blog for selenium-2 example.

Post a Comment