3

I want to get the style value from an element and assign it to a string var. I tried using the below code but it returns a value of 'rgb(173, 255, 47)' when I'm trying to return the value 'background:#ADFF2F"':

IWebElement highlightedText = _driver.FindElement(By.Id("firstHeading")).FindElement(By.CssSelector("th-highlight-span"));
actualHighlightColour = highlightedText.GetAttribute("style");

This is the src code from the web page I want to get the value of style from:

<h1 id="firstHeading" class="firstHeading" lang="en">
 ::before
 <th-highlight-span style="background:#ADFF2F" data- 
 rwstate="ss">California Proposition 218 (1996)</th-highlight-span>

The code I tried to use returns 'rgb(173, 255, 47)' which can be found here but I want to return background: #ADFF2F:

element.style {
background: #ADFF2F;
background-image: initial;
background-position-x: initial;
background-position-y: initial;
background-size: initial;
background-repeat-x: initial;
background-repeat-y: initial;
background-attachment: initial;
background-origin: initial;
background-clip: initial;
background-color: rgb(173, 255, 47);
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Tester_Giant1
  • 101
  • 3
  • 5

2 Answers2

1

Convert RGB to hex format

 String hex = String.format("#%02x%02x%02x", r, g, b);

This will return the hex in small alphabet and if want this in caps then simply replace x with X

Joshua
  • 5,901
  • 2
  • 32
  • 52
Pramod
  • 1,835
  • 8
  • 14
1

As per the HTML you have shared to retrieve the style attribute i.e. the text background:#ADFF2F you can use the following solution :

actualHighlightColour = _driver.FindElement(By.CssSelector("h1.firstHeading#firstHeading>th-highlight-span")).GetAttribute("style");

Update

As the above expression still returns background: rgb(173, 255, 47);, get the output as rgb(173, 255, 47) you can use the GetCssValue() method and you can use the following solution:

actualHighlightColour = _driver.FindElement(By.CssSelector("h1.firstHeading#firstHeading>th-highlight-span")).GetCssValue("background");

You can find a detailed discussion in How to convert #ffffff to #fff or #fff to #ffffff while asserting the background color rgb(255,255,255) returned by Selenium getCssValue(“background”)

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352