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

Extract Parent Text without Children Text; Parsing HTML

I have this small bit of a soup tag element that I pulled using Selenium & BeautifulSoup.

<footer>
    <p class="tags environment-tags">Environment:
      <span class="tag environment-tag">Desert</span>
    </p>
    <p class="source monster-source">Basic Rules
      <span class="page-number">, pg. 334</span>
    </p>
</footer>

I am trying to grab the Text from just the p elements, but every time I try it grabs the span as well. So far this is what I tried:

for p in Environment.findAll('p'):
    print(p.text)

I have also tried to extract the information using .extract() but that doesn’t seem to work for me.

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

>Solution :

You can use .contents and access the 0th element:

for tag in soup.find_all("p"):
    print(tag.contents[0].strip())

Output:

Environment:
Basic Rules

Or with your attempt, you can remove the <span>‘s using .extract() by:

for tag in soup.select("p span"):
    tag.extract()

print(soup.prettify())

Output:

<footer>
 <p class="tags environment-tags">
  Environment:
 </p>
 <p class="source monster-source">
  Basic Rules
 </p>
</footer>
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