python - 如何使用Selenium WebDriver和python获取Web元素的颜色? [英] How to get a color of a web element using Selenium WebDriver with python?

查看:57
本文介绍了python - 如何使用Selenium WebDriver和python获取Web元素的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I locate the background-color of a webelement in hexadecimal format? With my current selenium webdriver python code it is returning the background-color in RGB format.

这是我正在查看的 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 格式颜色的样式.我想专门获取十六进制格式的背景颜色,以便我可以将它与我的预期值进行比较.我现在得到以下输出:

It is returning the style with the colors in rgb format. I want to specifically get the background-color in hexadecimal format so that I can compare it with my expected value. I am getting the following output now:

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

推荐答案

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

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

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

However, this will return the string rgb(221, 81, 76). In order to get the hex value of it, 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)

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

And your hex color is the string #dd514c.

这篇关于python - 如何使用Selenium WebDriver和python获取Web元素的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆