09
Jul

Get CssValue / Attribute of an WebElement in selenium

Sometimes it is necessary to get the Attribute / run time value of Css property of a WebElement.

We can use following code-snippet to get run time value of a webElement in selenium

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.*;

public class GetBackgroundColor {
public static void main(String[] args) {
// Initiate Driver
WebDriver driver = new FirefoxDriver();
driver.get(“http://www.w3.org/Talks/2012/0416-CSS-WWW2012/Demos/transitions/demo-transitions-1.html#no_transition”);
String bgColor, fontSize, fontWeight;
WebElement WebElement1 = driver.findElement(By.xpath(“//li[@id=’no_transition’]”));
bgColor = WebElement1.getCssValue(“background-color”).toString();
System.out.println(bgColor);
fontSize = WebElement1.getCssValue(“font-size”).toString();
System.out.println(fontSize);
fontWeight=WebElement1.getCssValue(“font-weight”).toString();
System.out.println(fontWeight);
// Split css value of rgb
String[] numbers = bgColor.replace(“rgba(“, “”).replace(“)”, “”).split(“,”);
int number1 = Integer.parseInt(numbers[0]);
numbers[1] = numbers[1].trim();
int number2 = Integer.parseInt(numbers[1]);
numbers[2] = numbers[2].trim();
int number3 = Integer.parseInt(numbers[2]);
String hex = String.format(“#%02x%02x%02x”, number1, number2, number3);
System.out.println(hex);

}
}