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

Finding text from html using BeautifulSoup

I have the following .html:

<li class="print text">
                            <span><em class="time">
                                    <div class="time">1.29 s</div>
                                </em><em class="status">passed</em>This is the text I want to get</span>

I need to get only the text that is outside all of the other tags (text is: This is the text I want to get).

I was trying to use this piece of code:

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

for el in doc.find_all('li', attrs={'class': 'print text'}):
    print(el.get_text())

But unfortunatelly it prints everything including the em tags etc.

Is there any way to do this?

Thank you!!

>Solution :

You could go with find(text=True, recursive=False) to get your goal.

Example
from bs4 import BeautifulSoup
soup='''<li class="print text">
        <span><em class="time">
                <div class="time">1.29 s</div>
            </em><em class="status">passed</em>This is the text I want to get</span>'''

soup=BeautifulSoup(soup)

soup.find('li',class_='print text').span.find(text=True, recursive=False)

Output

This is the text I want to get

If there are multiple span in your li you could go with:

from bs4 import BeautifulSoup
soup='''<li class="print text">
        <span><em class="time">
                <div class="time">1.29 s</div>
            </em><em class="status">passed</em>This is the text I want to get</span>
            <span><em class="time">
                <div class="time">1.50 s</div>
            </em><em class="status">passed</em>This is the text I want to get too</span>'''

soup=BeautifulSoup(soup)

for e in soup.select('li.print.text span'):
    print(e.find(text=True, recursive=False))
Output
This is the text I want to get
This is the text I want to get too
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