如何使用 Selenium Python 获取文本颜色

4

我的目标是获取1个单列表中每个单元格文本的颜色。一个单元格的HTML如下:

<table class="table table-bordered table-hover">
<tbody>
      <tr>
           <td class="table-centerText"><font color="red">1</font> </td>
           <td class="table-centerText">22:06</td>
           <td class="table-centerText">10:17</td>
           <td class="table-centerText">55124</td>
           <td class="table-centerText">70.3</td>
           <td class="table-centerText">-35.2</td>
           <td> <a href="preview.php?datasetID=16709">View</a></td>
      </tr>
</tbody></table>

我用以下代码查找每列文本颜色:

pointing_list = driver.find_element_by_xpath("//table/tbody")
table_rows = []
table_rows = pointing_list.find_elements_by_tag_name("tr")
num_rows = len(table_rows) - 1
print(num_rows)

for x in range(num_rows):
total = 0
element = driver.find_element_by_xpath("//table/tbody/tr[%d]/td[1]" % (x + 2))
color = element.value_of_css_property("color")
print(color)

循环每次都检查正确的单元格,但颜色始终为“rgba(0, 0, 0, 1)”,这是错误的,因为文本颜色会更改且从未是黑色。我尝试用 background-color 替换了 color ,这样每个单元格都返回了正确的背景颜色。不幸的是,我需要文本颜色。 font-color text-color 也无法起作用。

1
看起来你可能需要进入“字体”标签才能获取颜色属性?但不确定。 - JD2775
3个回答

3

请将此更改为:

//table/tbody/tr[%d]/td[1]

to :

//table/tbody/tr[%d]/td[1]/font

然后获取颜色如下:

color = element.get_attribute("color")

2
可以通过 CSS 选择器来实现。只需获取 color 属性即可:
color = driver.find_element_by_css_selector(".table-centerText>font").get_attribute("color")

0

我会选择如此处所讨论的.value_of_css_property(),以及颜色十六进制转换此处

argb = find_element_xx('some selector xx').value_of_css_property('color')
hex  = Color.from_string(argb).hex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接