如何使用Selenium WebDriver和python获得web元素的颜色?

2024-05-06 16:51:15 发布

您现在位置:Python中文网/ 问答频道 /正文

如何以十六进制格式定位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%"

我的webdriver python代码是:

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

它以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%;

Tags: 代码imagetop格式rgbclasscolorlinear
3条回答

由于返回的格式与元组匹配,因此无需使用返回为“rgba”字符串的“re”即可实现:

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

如果字符串是“rgb”,只需省略“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

由于提出了最初的问题,现在首选的方法是使用selenium颜色支持模块:

一个简单的指南是here

你在找value_of_css_property('background-color')

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

但是,这将返回字符串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)

你的十六进制是字符串。

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))

收益率

DD514C

相关问题 更多 >