10

Web 要素の背景色を 16 進数形式で見つけるにはどうすればよいですか? 現在の 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%"

私のウェブドライバーのpythonコードは次のとおりです。

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

RGB形式の色でスタイルを返しています。期待値と比較できるように、背景色を16進数形式で具体的に取得したいと考えています。現在、次の出力が得られています。

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

4 に答える 4

15

あなたが探しているvalue_of_css_property('background-color')

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

ただし、これは string を返しますrgb(221, 81, 76)。16 進値を取得するには、@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)

そして、あなたの16進colorは文字列#dd514cです。

于 2013-02-27T16:53:00.850 に答える
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
于 2013-02-27T02:22:56.670 に答える
2

戻り値の形式はタプルと一致するため、これは、戻り値が「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

元の質問が提起されたため、推奨される方法は現在、セレン カラー サポート モジュールを使用することです。

簡単なガイドはこちら

于 2015-03-04T13:54:10.520 に答える