簡體   English   中英

如何確定Selenium中WebElement的有效CSS屬性?

[英]How to determine the effective CSS properties of a WebElement in Selenium?

我有以下 HTML 文檔(這是一個簡化的示例):

<!DOCTYPE html>
<html lang="en">
<head>
    ...
</head>
<body style="background-color: blue;">
    <div id="myDiv" style="color: white;">HEY</div>
</body>
</html>

我正在將此文檔加載到 chromedriver 中並嘗試確定元素#myDiv的有效背景顏色。 Selenium有沒有辦法做到這一點?

我嘗試過的顯而易見的事情:

final WebElement elem = driver.findElement(By.cssSelector("#myDiv"));
System.out.println(elem.getCssValue("background-color"));
// Prints rgba(0, 0, 0, 0), expected rgb(0, 0, 255) or equivalent

我還嘗試運行以下 Javascript,但同樣,這只會返回在元素本身上設置的屬性,而忽略父元素的 styles:

final WebElement elem = driver.findElement(By.cssSelector("#myDiv"));
final String computedStylePropertyScript = "return window.document.defaultView"
                 + ".getComputedStyle(arguments[0],null).getPropertyValue(arguments[1]);";
System.out.println((String) ((JavascriptExecutor) driver).executeScript(computedStylePropertyScript, elem, "background-color");
// Prints rgba(0, 0, 0, 0), expected rgb(0, 0, 255) or equivalent

有沒有辦法讀取WebElement在 selenium 中的背景(或前景)顏色的有效值?

這將更加困難。

rgba(0, 0, 0, 0)是正確的。 這意味着顏色是透明的並且取自父元素。

解決方案是查找父級的顏色。

這是一個示例 function。

private String getBGColor(WebElement elementToSearch) {
    WebElement current = elementToSearch;
    while(isTransparent(current.getCssValue("background-color"))) {
        if (current.getTagName().equals("body")) {
            return null;
        }
        // Find Parent
        current = current.findElement(By.xpath("./.."));
    }
    return current.getCssValue("background-color");
}

private boolean isTransparent(String color) {
    String colorMod = color.replaceAll("\\s+","").toLowerCase();
    return Arrays.asList("transparent","","rgba(0,0,0,0)").contains(colorMod);
}

調用它

WebElement elem = driver.findElement(By.cssSelector("#myDiv"));
System.out.println(getBGColor(elem));

暫無
暫無

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

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