【问题标题】:How to get text color using Selenium Python如何使用 Selenium Python 获取文本颜色
【发布时间】:2021-08-21 19:07:42
【问题描述】:

我的目标是从 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,它为每个单元格返回了正确的背景颜色。不幸的是,我需要文字颜色。将color 替换为font-colortext-color 也不起作用。

【问题讨论】:

  • 看起来您可能需要进入font 标签才能获取颜色属性?不过不确定。

标签: python html css selenium selenium-webdriver


【解决方案1】:

可以使用 css 选择器来完成。只需获取color 属性:

color = driver.find_element_by_css_selector(".table-centerText>font").get_attribute("color")

【讨论】:

    【解决方案2】:

    改变这个:

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

    到:

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

    得到这样的颜色:

    color = element.get_attribute("color")
    

    【讨论】:

      猜你喜欢
      • 2014-06-06
      • 1970-01-01
      • 2013-02-12
      • 1970-01-01
      • 2014-01-26
      • 2019-03-08
      • 2023-03-30
      • 2012-10-11
      • 1970-01-01
      相关资源
      最近更新 更多