首页 文章

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

提问于
浏览
8

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

This is the html element that I am looking at

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 webdriver python code is:

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 回答

  • 0

    您正在寻找 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)
    

    你的hex color 是字符串 #dd514c .

  • 2

    由于返回的格式与元组匹配,这是可以实现的,而不使用're',其中返回是'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
    

    字符串是'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
    

    自提出原始问题以来,首选方法是使用硒色支持模块:

    一个简单的指南是here

  • 10
    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
    
  • 0

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

相关问题