【问题标题】:How to determine the effective CSS properties of a WebElement in Selenium?如何确定 Selenium 中 WebElement 的有效 CSS 属性?
【发布时间】:2020-11-18 22:40:51
【问题描述】:

我有以下 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,但同样,这只会返回在元素本身上设置的属性并忽略父元素的样式:

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在硒中的背景(或前景)颜色的有效值?

【问题讨论】:

    标签: javascript java css selenium dom


    【解决方案1】:

    这将更加困难。

    rgba(0, 0, 0, 0) 是正确的。表示颜色是透明的,取自父元素。

    解决方案是查找父级的颜色。

    这是一个示例函数。

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

    【讨论】:

    • 感谢您的解释。我想避免基于 DOM 的计算,但您在透明度方面做得很好。我猜你的解决方案会在绝对定位的元素上失效,但这是我可以接受的不精确。
    猜你喜欢
    • 1970-01-01
    • 2021-08-17
    • 2015-05-02
    • 2016-07-28
    • 2017-04-28
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多