Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 751
a43nigam Avatar asked Nov 01 '25 08:11

a43nigam


2 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")
like image 123
cruisepandey Avatar answered Nov 03 '25 21:11

cruisepandey


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

color = driver.find_element_by_css_selector(".table-centerText>font").get_attribute("color")
like image 36
vitaliis Avatar answered Nov 03 '25 22:11

vitaliis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!