Get the text from the nested span tag with beautifulsoup

Viewed 296

I have an html file:

...
<span class="value">401<span class="Suffix">st</span></span>
...

and I want to get only first span tag text which is 401 but when I run:

>>> get_text = soup.find(class_ = 'value').text
>>> print(get_text)
401st

the output contains inner spans text(st).

3 Answers

Use .strings. This is a @property that gives a generator of individual string elements. .text or .get_text is what joins those strings together.

>>> soup = bs4.BeautifulSoup('<span class="value">401<span class="Suffix">st</span></span>')
>>> t = soup.find(class_='value')
>>> next(t.strings)
'401'
>>> list(t.strings)
['401', 'st']

You need to use recursive=False in BeautifulSoup

<span class="value">401<span class="Suffix">st</span></span>
soup = BeautifulSoup(html)

all_parent_p = soup.find_all('p', recursive=False)
for parent_p in all_parent_p:
   ptext = parent_p.find(text=True, recursive=False)

This will work fine:

from bs4 import BeautifulSoup
s = '''<span class="value">401<span class="Suffix">st</span></span>'''
soup = BeautifulSoup(s, 'html.parser')
get_text = soup.find(class_='value')
print(get_text.contents[0])

Output

401
Related