2012-07-10 19 views
1

我想計算具有特定背景顏色的字符數。要知道,我經歷了所有的HTML節點行走使用此解決方案:Counting inner text letters of HTML elementSelenium - 確定透明HTML對象的背景顏色

HTML頁面:

<span style="background-color: #ffff00;"> 
    <span id="child">I inherit the background color but Selenium gives me back transparent</span> 
    </span> 

硒例:

FirefoxDriver firefoxDriver = new FirefoxDriver(); 
// firefoxDriver.get(...); 

WebElement element = firefoxDriver.findElement(By.id("child")); 
final String cssValue = element.getCssValue("background-color"); 

System.out.println("TextColor of the Child Element: " + cssValue); 

的問題是現在,認爲System.out的打印「透明」作爲CSS值而不是#ffff00作爲背景色。

我現在需要一些代碼來查找父級的值,在這種情況下。如果父母也有「透明」的價值,那麼它應該繼續這樣下去。

我使用的是Java 7,但可以執行每個Selenium的JavaScript代碼。

回答

0

在CSS中,默認情況下並不總是繼承。在你的情況下,內部跨度不會繼承背景顏色,除非你專門告訴它。

我已經做了兩個jsFiddles來證明這一點:

沒有繼承: http://jsfiddle.net/vLXfr/

有了繼承: http://jsfiddle.net/B67Bm/

正如你所看到的值送回僅僅是一樣的父母背景顏色,如果你告訴孩子元素繼承背景顏色。

UPDATE:

說完看着你添加的源有您需要回答幾個問題,但是這是可能的。

這是一個醜陋的算法,我沒有硒在我面前,所以你必須檢查默認值。基本思想是通過DOM來查看父母/祖父母/祖父母/祖父母/祖父母/祖父母/祖父母/祖父母/祖父母/祖父母/祖父母/祖父母/

public String getParentBackgroundColor(WebElement element) { 
    WebElement current = element; 
    //Ugly while true loop, fix this 
    while(true) { 
     //Get the current elements parent 
     WebElement parent = element.findElement(By.xpath("..")); 

     //If the parent is null then doesn't have a parent so we should stop (change to seleniums default if element doesn't have a parent) 
     if (parent == null) { 
      throw new WeFailedException("Sorry, no parent elements had a background-color set"); 
     } else { 
      //Otherwise get the parents color 
      String color = parent.getCssValue("background-color"); 
      //If the color is transparent (based off your description, this could be some other default value) then set the parent as the current and continue the loop to try and get the parents parents color 
      if (color == "transparent") { 
       current = parent; 
      } else { 
       //If we found a color return it 
       return color; 
      } 
     } 
    } 
} 

然後,您可以用這個和你內心的跨度傳遞給它,它應該回到父母的顏色。

希望這會有所幫助。

+0

問題是,我想獲取內部HTML對象的背景顏色,雖然它設置爲「透明」。 – 2012-07-10 13:58:49

+0

內部元素的背景顏色是透明的,我的第一個jsFiddle證明了這一點。由於你沒有設置它,它不會繼承父母顏色,所以它會作爲你使用的函數的默認返回類型返回,在jQuery中這是rgba(0,0,0,0),即一個空的透明黑色顏色。 – 2012-07-10 14:02:31

+0

正是這是我的問題,我喜歡確定真正的背景色,在我們的情況下,由父母給出,使用Selenium – 2012-07-10 14:05:16