Automation Using Selenium Webdriver
Showing posts with label How To Get Height And Width Of Element In Selenium WebDriver. Show all posts
Showing posts with label How To Get Height And Width Of Element In Selenium WebDriver. Show all posts

Saturday 15 October 2016

How To Get Height And Width Of Element In Selenium WebDriver

As you know, Every web element has Its own height and width or we can say size element. Sometimes you need to perform pixel to pixel testing as per client's requirement like each and every button's height should be x(some pixels) and width should be y(some pixels) through out the site. 

Now If you go for measuring height and width of every element manually then It Is time consuming on every test cycle. Automation Is best solution to measure height and width of elements because It Is one time exercise and then you can use It In every test cycle.
We have learnt how to get x y coordinates of element using selenium web driver In previous post. Now let us learn how to get size of element. I have prepared simple example to explain
 you how to get height and width of Image In selenium web driver. As you can see In bellow example, I have used getSize() method to get height and width of element.

package Testing_Pack;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class getElementSize {
 WebDriver driver;
 @BeforeTest
 public void setup() throws Exception {
  driver =new FirefoxDriver();     
  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.get("http://any web page");
 }

 @Test
 public void getSize() throws Exception {
  //Locate element for which you wants to get height and width.
        WebElement Image = driver.findElement(By.xpath("//img[@border='0']"));
        
        //Get width of element.
        int ImageWidth = Image.getSize().getWidth();
        System.out.println("Image width Is "+ImageWidth+" pixels");
        
        //Get height of element.
        int ImageHeight = Image.getSize().getHeight();        
        System.out.println("Image height Is "+ImageHeight+" pixels");
 }
}

When you run above test In eclipse, It will print height and width of
 element In console as bellow.
OutPut::
Image width Is 212 pixels
Image height Is 191 pixels