python-beautifulsoup same td attributes to different lists

I'm new to python beautiful soup and I've tried to find an answer for my question for a long time.

I try to scrape data from a website, it has many tables and td's. There are 2 td's with the same attributes but different data usage for me. How can I differ between them when I get all those td's? The goal is to store them in different lists.

The HTML looks like this:

<td class = "xyz">
  <h4 class = "zyw">
    " 1"
   <small class = "unit">" m" </small>
  </h4>
</td>
<td class = "xyz">
  <h4 class = "zyw">
    " 8"
   <small class = "unit">" s" </small>
  </h4>
</td>

I manage to get the data of both with the following code:

for td_swellHeight in tr.find_all('td', {'class':'text-center background-gray-lighter'}):
        for h4_swellHeight in td_swellHeight.find_all('h4'):
            print(h4_swellHeight.text)

the output would look like this:

enter image description here

Thanks!


Solution 1:

You could use an index to skip every second td:

for i,td_swellHeight in enumerate(tr.find_all('td', {'class':'text-center background-gray-lighter'})):
    if i % 2 == 0:
        continue
    for h4_swellHeight in td_swellHeight.find_all('h4'):
        print(h4_swellHeight.text)