Get the style of a web object using selenium webdriver

There are too many posts on this topic but they are all scattered in bits and pieces, bringing it all to one place to solve how to get the background color or any other css property of an element using webdriver

These days elements are rarely styled with just inline styles. For example:
<div style="color:red">text</div>
An element’s style will also be dependent on its parent elements, as well as its class (ie style sheets).
<div style="color:red">
  <span class="bigtext">text</span>
How do you get the actual style of the element (ie the computed style)?
For example color
WebElement elem = driver.findElement(By.xpath("//a[contains(@class,'test')]")); System.out.println(elem.getCssValue("color")); System.out.println(elem.getCssValue("background-color")); String color = elem.getCssValue("color"); String s1 = color.substring(5); StringTokenizer st = new StringTokenizer(s1); int r = Integer.parseInt(st.nextToken(",").trim()); int g = Integer.parseInt(st.nextToken(",").trim()); int b = Integer.parseInt(st.nextToken(",").trim()); Color c = new Color(r, g, b); String hex = "#"+Integer.toHexString(c.getRGB()).substring(2); System.out.println(Color.decode(hex)); WebElement element = driver.findElement("color"));
Note that shorthand CSS properties (e.g. background, font, border, border-top, margin, margin-top, padding, padding-top, list-style, outline, pause, cue) are not returned, in accordance with the DOM CSS2 specification- you should directly access the longhand properties (e.g. background-color) to access the desired values.

Popular posts from this blog

Trim / Remove spaces in Xpath?

RPA - Blue Prism, OpenSpan, Automation Anywhere vs UIPath