How to get element color with Selenium How to get element color with Selenium selenium selenium

How to get element color with Selenium


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


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.


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