How to get text color using Selenium Python

Viewed 859

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.

3 Answers

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

It can be done with css selectors. Just get color attribute:

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

I would go for .value_of_css_property() as discussed here, and color hex converted here

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