selenium获得元素的自然高度和宽度。 不应该依赖style属性。 GetSize(),GetLocation()和getRect()都无法执行此操作

这是场景。

当我使用GetSize(),GetLocation()函数对图像ID’FlashID1x’时它总是给出250,300,但元素的实际高度和宽度是1 X 1,这基本上是错误的。

这是我的目标dom:

 

这是我的代码:

 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()); 

getSize方法返回呈现的Web元素大小,而不是图像的物理大小。 如果你的目标是获得内在的高度和重量,那么你可以尝试获得naturalWidth和naturalHeight属性:

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

无论图像本身的大小如何,从WebDriver规范中可以清楚地看出,它是确定元素维度的CSS,同样适用于其他每种元素的规则。

我认为这很公平。 你的标记显然与底层图像不匹配,但可能有一些我们无法看到的理由。 由于元素的膨胀大小会对其他元素的定位产生影响,因此WebDriver准确报告位置是合理的,而不是假装它们整齐地隐藏在一个小方块旁边。

如果您需要解决方法:您可以创建一个getImageRect()方法,该方法具有针对该URL模式或Id的特殊覆盖,您可以使用HTTP库在启动时检查实际图像的大小并对其进行缓存,或者您可以简单地对1×1进行硬编码。