如何使用Python的Selenium WebDriver获取网页元素的颜色?

13 投票
4 回答
48320 浏览
提问于 2025-04-17 17:15

我该如何找到网页元素的背景颜色,并以十六进制格式显示呢?我现在用的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%;

4 个回答

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

产生

8

要转换颜色,你可以直接使用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

Selenium文档

19

你想要获取 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)

那么你的十六进制 color 就是字符串 #dd514c

撰写回答