有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用Selenium获取元素颜色

我想检查html页面中元素的颜色。 这个元素的颜色是用javascript设置的,请看图片enter image description here

div id为“Ab_banco_M1T1_switch”的元素可以假设4个值,当然,根据“val”变量的值,只显示其中一个值。 val变量是从服务器设置的,它显示脚本每隔X秒轮询服务器一次,并更新val的值

我试图获得元素的颜色,如下所示:

WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("Ab_banco_M1T1_switch")));

element.getAttribute("background")
element.getAttribute("style")
element.getAttribute("background-color") 
element.getCssValue("style")
element.getCssValue("color")

如果没有成功,它们将返回“null”或页面的背景颜色

获取颜色的唯一方法是使用Xpath /html/body/div/div[2]/div[2]/div[2]/div/div/div/div[3]/div (for red, if I want the green /html/body/div/div[2]/div[2]/div[2]/div/div/div/div[2]/div)

但这不是我想要的。确实,Xpath将元素本地化,但它不会告诉我显示的颜色是红色还是其他颜色,我只能通过查看网页才能知道

换句话说,我想像Firebug一样访问当前显示的颜色,看看右侧的面板,您可以看到element.style ->background-Color = red

当我调用元素时,getCssCValue("background-color")我得到了#body_right_div的背景颜色

先谢谢你


共 (4) 个答案

  1. # 1 楼答案

    试试这个,非常适合我:

    import org.openqa.selenium.support.Color;
    
    String color = driver.findElement(By.xpath("xpath_value")).getCssValue("color");
    System.out.println(color);
    String hex = Color.fromString(color).asHex();
    System.out.println(hex);
    

    因此,您可以使用getCssValue("color");getCssValue("background-color");获得颜色。 然而,这将是在RGB,所以你需要转换为十六进制。使用十六进制代码,您可以比较该值并将其打印出来,这样您就可以看到在每次getCssValue之后得到的结果

  2. # 2 楼答案

    使用XPath,您可以尝试按属性进行搜索。例如//div[@style='background: red']。如果您想获得颜色,那么对于CSS,我将使用方法getCSSValue()

  3. # 3 楼答案

    您可以通过以下方式获取元素颜色(元素的背景色):

    element.getCssValue("background-color");
    

    您可以通过以下方式获取元素文本/标题颜色:

    element.getCssValue("color");
    

    例如,如果要获取LinkedIn“登录”按钮的背景和文本颜色,代码如下:

    driver.get("https://www.linkedin.com/");
            String buttonColor = driver.findElement(By.name("submit")).getCssValue("background-color");
            String buttonTextColor = driver.findElement(By.name("submit")).getCssValue("color");
            System.out.println("Button color: " + buttonColor);
            System.out.println("Text color " + buttonTextColor);
    
  4. # 4 楼答案

    尝试下面的代码

    public String ColorVerify(String cssSelector, String cssValue)
    {
        /* This method used to verify color code*/
        WebElement target = driver.findElement(By.cssSelector(cssSelector));
        String colorCode= target.getCssValue(cssValue);
        String hexacolor = Color.fromString(colorCode).asHex();
        return hexacolor;   
    }