Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Get Sibling <td> Tag Texts from Span Tag in Python/BeautifulSoup

In the following HTML example, I like to retrieve texts from all the sibling tags to the first TD tag containing a span tag text of "EPS Actual", ie, {1.1 , 2.2, 3.3, 4.4}. My codes below didn’t work. How can I do that?

HTML sample:

<tr>
   <td>
      <span>EPS Actual</span>
   </td>
   <td>1.1</td>
   <td>2.2</td>
   <td>3.3</td>
   <td>4.4</td>
</tr>
import requests
from bs4 import BeautifulSoup

soup = BeautifulSoup(html, 'lxml')
epsActual = soup.find('span', text='EPS Actual').find_next_siblings('td').text

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

td_tag = soup.find('td', text='EPS Actual')
sibling_td_tags = td_tag.find_next_siblings('td')
texts = [tag.text for tag in sibling_td_tags]

print(texts)  # Output: ['1.1', '2.2', '3.3', '4.4']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading