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

Question:

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
Asked By: Newbie

||

Answers:

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']
Answered By: Adelina
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.