How to get element color with Selenium

前端 未结 4 1813
走了就别回头了
走了就别回头了 2020-12-18 00:34

I want to check the color of an element in an html page. The color of this element is set with a javascript, look at the image

The element with div-id \"Ab_banco_M

相关标签:
4条回答
  • 2020-12-18 01:07

    You can get the element color(Background color of element) by:

    element.getCssValue("background-color");
    

    You can get the element text/caption color by:

    element.getCssValue("color");
    

    For example if you want to get the background and text color of "Sign in" button for LinkedIn, the code is as follows:

    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);
    
    0 讨论(0)
  • 2020-12-18 01:10

    Try below code

    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;   
    }
    
    0 讨论(0)
  • 2020-12-18 01:11

    With XPath you can try to search by attribute. For example //div[@style='background: red']. If you want to get color then for CSS I would use method getCSSValue()

    0 讨论(0)
  • 2020-12-18 01:18

    try this, worked perfect for me:

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

    So you can get color using getCssValue("color"); and getCssValue("background-color");. However, that would be in RGB, so you need to convert to hex. With hex code you can then compare the value and print it out so that you can see what you are getting after each getCssValue.

    0 讨论(0)
提交回复
热议问题