如何使用Selenium WebDriver和python获取Web元素的颜色?

nid*_*ids 9 python selenium automation selenium-webdriver

如何以十六进制格式找到webelement的背景颜色?使用我当前的selenium webdriver python代码,它返回RGB格式的背景色.

这是我正在看的html元素

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%"
Run Code Online (Sandbox Code Playgroud)

我的webdriver python代码是:

find_element_by_class_name("bar").get_attribute("style")
Run Code Online (Sandbox Code Playgroud)

它以rgb格式返回颜色样式.我想专门以十六进制格式获取背景颜色,以便我可以将它与我的预期值进行比较.我现在得到以下输出:

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%;
Run Code Online (Sandbox Code Playgroud)

Car*_*s V 11

您正在寻找value_of_css_property('background-color'):

rgb = find_element_by_class_name("bar").value_of_css_property('background-color')
Run Code Online (Sandbox Code Playgroud)

但是,这将返回字符串rgb(221, 81, 76).为了获得它的十六进制值,你可以使用@ unutbu的答案:

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)
Run Code Online (Sandbox Code Playgroud)

你的十六进制color是字符串#dd514c.


小智 6

要转换颜色,可以直接使用 selenium 的 Color 类:

from selenium.webdriver.support.color import Color

rgb = find_element_by_class_name("bar").value_of_css_property('background-color')
hex = Color.from_string(rgb).hex
Run Code Online (Sandbox Code Playgroud)

硒文档


unu*_*tbu 2

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))
Run Code Online (Sandbox Code Playgroud)

产量

DD514C
Run Code Online (Sandbox Code Playgroud)