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'
.
CodePudding user response:
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.
CodePudding user response:
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