簡體   English   中英

Selenium 獲取元素的自然高度和寬度。 不應依賴樣式屬性。 GetSize()、GetLocation() 和 getRect() 未能這樣做

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

這是場景。

當我對圖像 ID 'FlashID1x' 使用 GetSize()、GetLocation() 函數時,它總是給出 250,300,但元素的實際高度和寬度是 1 X 1,這基本上是錯誤的。

這是我的目標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"/>

這是我的代碼:

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 規范中可以清楚地看出,決定<img>元素尺寸的是 CSS,同樣的規則適用於所有其他類型的元素。

我認為這很公平。 您的標記顯然與底層圖像不匹配,但大概有一些我們看不到的理由。 由於您元素的膨脹尺寸會影響其他元素的位置,因此 WebDriver 准確報告它們的位置是公平的,而不是假裝它們整齊地塞在一個小方塊旁邊。

如果您需要解決方法:您可以為該 URL 模式或 Id 創建一個帶有特殊覆蓋的getImageRect()方法,您可以使用 HTTP 庫在啟動時檢查真實圖像的大小並將其緩存,或者您可以簡單地硬編碼 1x1。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM