Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 256
arcee123 Avatar asked Nov 28 '14 20:11

arcee123


1 Answers

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'
like image 150
dreyescat Avatar answered Oct 17 '22 05:10

dreyescat