Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium get natural height and width of an element. should not rely on style attribute. GetSize(), GetLocation() and getRect() fails to do so

Here is the scenario.

When am using GetSize(), GetLocation() Functions against the image ID 'FlashID1x' its always giving 250,300 but the actual height and width of an element is 1 X 1 which is basically wrong.

Here is my target dom:

<img id="FlashID1x" border="0" width="300" height="250" style="width:300px;height:250px;" alt="" src="http://s2.adform.net/Banners/invisible.gif?bv=2"/>

Here is my code:

System.out.println("total : "+iframe.size());  
//driver.switchTo().frame(frame);

org.openqa.selenium.Point point=driver.findElement(By.xpath(".//*[@id='FlashID1x']")).getLocation();  
System.out.println("X Position : "+point.x);  
System.out.println("Y Position : "+point.y);  

System.out.println("X getX : "+point.getX());  
System.out.println("Y gety : "+point.getY());  

Rectangle pointer=driver.findElement(By.xpath(".//*[@id='FlashID1x']")).getRect();
System.out.println("height : "+pointer.hashCode();
System.out.println(" width : "+pointer.getWidth());  

System.out.println("getHeight : "+pointer.getHeight());  
System.out.println(" getWidth : "+pointer.getWidth());  
like image 223
Maniraj Mkr Avatar asked Mar 29 '16 13:03

Maniraj Mkr


1 Answers

The getSize method returns the rendered web element size and not the physical size of an image. If your goal is to get the intrinsic heigh and weight, then you could try to get the naturalWidth and naturalHeight properties:

WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, 20);
driver.get("http://stackoverflow.com");

// get the intrinsic size with the getAttribute method
WebElement ele = driver.findElement(By.cssSelector("img"));
String naturalWidth = ele.getAttribute("naturalWidth");
String naturalHeight = ele.getAttribute("naturalHeight");

// get the intrinsic size with a piece of Javascript
ArrayList result = (ArrayList)((JavascriptExecutor) driver).executeScript(
        "return [arguments[0].naturalWidth, arguments[0].naturalHeight];", ele);
Long naturalWidth2 = (Long)result.get(0);
Long naturalHeight2 = (Long)result.get(1);
like image 181
Florent B. Avatar answered Oct 02 '22 19:10

Florent B.