How to get web element color using Selenium WebDriver using python?

How to find the background color of a web element in hexadecimal format? With my current selenium webdriver python code, it returns the background color in RGB format.

This is the html element I'm viewing

div class="bar" style="background-color: #DD514C; background-image: -moz-linear-gradient(center top , #EE5F5B, #C43C35); background-image: -webkit-linear-gradient(top , #EE5F5B, #C43C35); background-image: -ms-linear-gradient(top , #EE5F5B, #C43C35); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#EE5F5B, endColorstr=#C43C35, GradientType=0); background-repeat: repeat-x; color: #ffffff; width: 11.5%" 

My python code for webdriver:

 find_element_by_class_name("bar").get_attribute("style") 

It returns a style with colors in rgb format. I want to get the background color in hexadecimal so that I can compare it with my expected value. Now I get the following result:

 background-color: rgb(221, 81, 76); background-image: -moz-linear-gradient(center top , rgb(238, 95, 91), rgb(196, 60, 53)); background-repeat: repeat-x; color: rgb(255, 255, 255); width: 11.5%; 
+8
python selenium automation selenium-webdriver
source share
3 answers

You are looking for value_of_css_property('background-color') :

 rgb = find_element_by_class_name("bar").value_of_css_property('background-color') 

However, this will return the string rgb(221, 81, 76) . To get the hex value, you can use @unutbu's answer:

 import re ... rgb = find_element_by_class_name("bar").value_of_css_property('background-color') r,g,b = map(int, re.search( r'rgb\((\d+),\s*(\d+),\s*(\d+)', rgb).groups()) color = '#%02x%02x%02x' % (r, g, b) 

And your hex color is the line #dd514c .

+9
source share

Since the return format matches the tuple, this is achieved without using 're', where return is the string 'rgba':

 import ast rgba = element.value_of_css_property("background-color") r, g, b, alpha = ast.literal_eval(rgba.strip("rgba")) hex_value = '#%02x%02x%02x' % (r, g, b) return hex_value, alpha 

If the string "rgb" just omits "alpha"

 import ast rgb = element.value_of_css_property("background-color") r, g, b = ast.literal_eval(rgb.strip("rgb")) hex_value = '#%02x%02x%02x' % (r, g, b) return hex_value 

Since the original question was raised, the preferred method is to use the selenium color support module:

A simple reference here

+2
source share
 import re # style = find_element_by_class_name("bar").get_attribute("style") style = 'background-color: rgb(221, 81, 76); background-image: -moz-linear-gradient(center top , rgb(238, 95, 91), rgb(196, 60, 53)); background-repeat: repeat-x; color: rgb(255, 255, 255); width: 11.5%;' r,g,b = map(int, re.search( r'background-color: rgb\((\d+),\s*(\d+),\s*(\d+)\)', style).groups()) print('{:X}{:X}{:X}'.format(r, g, b)) 

gives

 DD514C 
0
source share

All Articles