Skip to content Skip to sidebar Skip to footer

BeautifulSoup Find The Next Specific Tag Following A Found Tag

Given the following (simplified from a larger document) Age 16

Solution 1:

if you get list of elements then you can use [index] to get element from list.

data = """<tr class="row-class">
  <td>Age</td>
  <td>16</td>
</tr>
<tr class="row-class">
  <td>Height</td>
  <td>5.6</td>
</tr>
<tr class="row-class">
  <td>Weight</td>
  <td>103.4</td>
</tr>"""

from bs4 import BeautifulSoup

soup = BeautifulSoup(data)

trs = soup.find_all("tr", {"class":"row-class"})

for tr in trs:
    tds = tr.find_all("td") # you get list

    print('text:', tds[0].get_text()) # get element [0] from list
    print('value:', tds[1].get_text()) # get element [1] from list

result

text: Age
value: 16
text: Height
value: 5.6
text: Weight
value: 103.4

Post a Comment for "BeautifulSoup Find The Next Specific Tag Following A Found Tag"