How to verify color of a web element in Selenium Webdriver?

SeleniumAutomation TestingTesting Tools

We can verify the color of a webelement in Selenium webdriver using the getCssValue method and then pass color as a parameter to it. This returnsthe color in rgba() format.

Next, we have to use the class Color to convert the rgba() format to Hex. Let us obtain the color an element highlighted in the below image. The corresponding color for the element is available under the Styles tab in Chrome browser.

The color of the element is also provided in the hex code #797979.

Syntax

WebElement t = driver.findElement(By.tagName("h1"));
String s = t.getCssValue("color");
String c = Color.fromString(s).asHex();

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.Color;
public VerifyColor{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify text
      WebElement t = driver.findElement(By.tagName("h1"));
      //obtain color in rgba
      String s = t.getCssValue("color");
      // convert rgba to hex
      String c = Color.fromString(s).asHex();
      System.out.println("Color is :" + s);
      System.out.println("Hex code for color:" + c);
      driver.quit();
   }
}

Output

raja
Published on 03-Apr-2021 14:32:59
Advertisements