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
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 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;
}
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()
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
.