arcee123
arcee123

Reputation: 211

how to get text from within a tag, but ignore other child tags

I am working with beautiful soup. I have a html string:

<div><b>ignore this</b>get this</div>

How do I retrieve "get this", while ignoring "ignore this"

Thanks

Upvotes: 15

Views: 12442

Answers (2)

lam vu Nguyen
lam vu Nguyen

Reputation: 629

def getonlytext(s):
    beg_tag = s.find('<')
    while not beg_tag == -1:
        fin_tag = s.find('>')
        s = s.replace(s[beg_tag:fin_tag+1], '')
        beg_tag = s.find('<')
    return s

Upvotes: 0

dreyescat
dreyescat

Reputation: 13798

You can get the div text just not recursively retrieving the children texts:

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('<div><b>ignore this</b>get this</div>')
>>> soup.div.find(text=True, recursive=False)
u'get this'

This works independently of the position of the text with respect of the children:

>>> soup = BeautifulSoup('<div>get this<b>ignore this</b></div>')
>>> soup.div.find(text=True, recursive=False)
u'get this'

Upvotes: 24

Related Questions