2

特定の背景色の文字数を数えたい。このソリューションを使用してすべてのHTMLノードをウォークスルーすることを理解するには: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がbackground-colorの#ffff00ではなくcss値として「transparent」を出力することです。

この場合、親の値を探すためのコードが必要になります。親も値として「透明」を持っている場合、それはそのように続くはずです。

私はJava7を使用していますが、SeleniumごとにJavaScriptコードを実行できます。

4

1 に答える 1

0

CSSでは、値はデフォルトで常に継承されるとは限りません。あなたの場合、特に指示しない限り、内側のスパンは背景色を継承しません。

これを証明するために、2つのjsFiddleを実行しました。

継承なし:http: //jsfiddle.net/vLXfr/

継承あり:http: //jsfiddle.net/B67Bm/

ご覧のとおり、子要素に背景色を継承するように指示した場合、返される値は親の背景色と同じになります。

アップデート:

追加したソースを確認した後、答える必要のあるいくつかの質問がありますが、これは可能です。

これは醜いアルゴリズムであり、目の前にセレンがないため、デフォルト値を確認する必要があります。基本的な考え方は、色が設定されている親要素を見つけて返すまで、親/祖父母/曽祖父母を調べて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;
            }
        }
    }
}

次に、これを使用して内側のスパンを渡すと、親の色が返されます。

お役に立てれば。

于 2012-07-10T13:53:57.283 に答える