aeiou
aeiou

Reputation: 447

Find a value in next td tag with bs4

Any way to pick the value 6.543 (ignoring <b>), belonging to next <td> after Hello Friend ?

 <tr>
  <td align="right" colspan="4">
   Hey Hello Friend
  </td>
  <td align="right">
   2.123
  </td>
 </tr>
 <tr>
  <td align="right" colspan="4">
   <b>
    Hello Friend 
    <sup>
     3
    </sup>
   </b>
  </td>
  <td align="right">
   <b>
    6.543
   </b>
  </td>
 </tr>

Note there is 'Hey Hello Friend' and 'Hello Friend '.

Using soup.find("td", text=re.compile("Hello Friend ")).find_next_sibling("td") does not work. It returns AttributeError: 'NoneType' object has no attribute 'find_next_sibling'.

Upvotes: 1

Views: 50

Answers (2)

Andrej Kesely
Andrej Kesely

Reputation: 195428

Another method using only CSS selectors:

print(soup.select_one('td:has(b:-soup-contains("Hello Friend")) + td').get_text(strip=True))

Prints:

6.543

Upvotes: 1

Barry the Platipus
Barry the Platipus

Reputation: 10460

Your code is looking for the element containing that text (in this case, a b tag) sibling: that <b> tag has no <td> sibling. What you need is:

soup.find("b", text=re.compile("Hello Friend")).find_next("td")

See BeautifulSoup documentation here.

Upvotes: 1

Related Questions