Skip to content
Advertisement

How to get text color using Selenium Python

My goal is to get the color of the text from each cell in 1 column table. The HTML for a single cell looks like this:

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

My code to find the text color of each column looks like this:

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)

The loop does check the correct cell in each iteration, but the color is always “rgba(0, 0, 0, 1)” which is wrong because the text color changes and is never black. I tried replacing color with background-color, which returned the correct background color for each cell. Unfortunately, I need the text color. Replacing color with font-color or text-color doesn’t work either.

Advertisement

Answer

Change this :

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

to :

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

and get the color like this :

color = element.get_attribute("color")
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement