Вам нужно будет работать с .find()
или .find_all()
, независимо от того, хотите ли вы включить дочерние теги или нет, используйте параметр recursive
:
html_code = """
<body>
<h1>hello<b>there</b>how are you?</h1>
</body>"""
import bs4
soup = bs4.BeautifulSoup(html_code, 'html.parser')
body_text = soup.body.find_all(text=True, recursive=False)
h1_text = soup.h1.find_all(text=True, recursive=True)
b_text = soup.b.find_all(text=True, recursive=False)
body_text = ' '.join(body_text).strip()
h1_text = ' '.join(h1_text).strip()
b_text = ' '.join(b_text).strip()
print ('body: %s\nh1: %s\nb: %s' %(body_text, h1_text, b_text))
Вывод:
body:
h1: hello there how are you?
b: there