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

How to get tag contents (including all text and elements)

I have a html snippet (no other parent elements):

html = '<div id="mydiv"><p>Hello</p><p>Goodbye</p>[...]</div>'

How do I extract all the tags and text (which may be variable) within the div, but not the div tag itself? I.e.L

target_str = '<p>Hello</p><p>Goodbye</p>[...]'

I have tried:

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

soup = BeautifulSoup(html , 'html.parser')
mydiv = soup.find(id='mydiv')
print(mydiv)
>>> '<div id="mydiv"><p>Hello</p><p>Goodbye</p>[...]</div>'

mydiv.unwrap()
print(mydiv)
>>> '<div id="mydiv"></div>'

How do I get just the contents of the tag?

>Solution :

Try:

from bs4 import BeautifulSoup

html = '<div id="mydiv"><p>Hello</p><p>Goodbye</p>[...]</div>'
soup = BeautifulSoup(html, "html.parser")

print("".join(map(str, soup.select_one("#mydiv").contents)))

Prints:

<p>Hello</p><p>Goodbye</p>[...]
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