Piotrek Leśniak
Piotrek Leśniak

Reputation: 83

Iterate over tds in ths in BS4 object

I have BS4 object like this:

<table border="0" class="dataframe comparison_for_values">
   <thead>
      <tr style="text-align: center;">
         <th>System</th>
         <th>Date</th>
         <th>value sum 1</th>
         <th>value sum 2</th>
         <th>value diff</th>
         <th>value diff in %</th>
      </tr>
   </thead>
   <tbody>
      <tr>
         <td>System 1</td>
         <td>0</td>
         <td>0</td>
         <td>0</td>
         <td>0</td>
         <td>0</td>
      </tr>
      <tr>
         <td>System 2</td>
         <td>5</td>
         <td>-240</td>
         <td>-244</td>
         <td>4</td>
         <td>-1.82</td>
      </tr>
      <tr>
         <td>System 3</td>
         <td>10</td>
         <td>-261</td>
         <td>-245</td>
         <td>-16</td>
         <td>6.31</td>
      </tr>
   </tbody>
</table>

I want to format last 2 td in each tr when value is different than 0 (by adding a class attribute). I don't know how to iterate over the tds in the trs in tbody only without also changing the ths.

How to do it?

Upvotes: 0

Views: 88

Answers (1)

intedgar
intedgar

Reputation: 681

Imagine your beautiful soup object is called soup. Then you could achieve this with the following code:

from bs4 import BeautifulSoup
trs = soup.find_all("tr")
for tr in trs:
    tds = tr.find_all("td")
    last_two_start = max(len(tds)-2,0)
    for i in range(last_two_start, len(tds)):
       if tds[i].get_text() != "0":
            tds[i]["class"]= "New_Class"

When you then look at soup via print(soup) you get the output:

<table border="0" class="dataframe comparison_for_values">
 <thead>
  <tr style="text-align: center;">
   <th>
    System
   </th>
   <th>
    Date
   </th>
   <th>
    value sum 1
   </th>
   <th>
    value sum 2
   </th>
   <th>
    value diff
   </th>
   <th>
    value diff in %
   </th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>
    System 1
   </td>
   <td>
    0
   </td>
   <td>
    0
   </td>
   <td>
    0
   </td>
   <td>
    0
   </td>
   <td>
    0
   </td>
  </tr>
  <tr>
   <td>
    System 2
   </td>
   <td>
    5
   </td>
   <td>
    -240
   </td>
   <td>
    -244
   </td>
   <td class="New_Class">
    4
   </td>
   <td class="New_Class">
    -1.82
   </td>
  </tr>
  <tr>
   <td>
    System 3
   </td>
   <td>
    10
   </td>
   <td>
    -261
   </td>
   <td>
    -245
   </td>
   <td class="New_Class">
    -16
   </td>
   <td class="New_Class">
    6.31
   </td>
  </tr>
 </tbody>
</table>

Upvotes: 1

Related Questions