Remove text that is not inside a tag in html

Viewed 53

I have an html like this :

text = """<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>
. remove me 
</body>
</html>"""

What i want to do is to remove anything that is not inside a tag (. remove me) in this case

my code so far :

from bs4 import BeautifulSoup
text = """<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>
. remove me
</body>
</html>"""
soup = BeautifulSoup(text,"html.parser")
print("".join(soup.strings))

But it doesn't remove it

Expected Output :

<!DOCTYPE html>
    <html>
    <body>
    
    <h1>My First Heading</h1>
    <p>My first paragraph.</p>
    </body>
    </html>
1 Answers

Try:

from bs4 import BeautifulSoup

text = """<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>
. remove me 
</body>
</html>"""

soup = BeautifulSoup(text, "html.parser")

for txt in soup.body.find_all(text=True, recursive=False):
    if not txt.strip():
        continue
    txt.replace_with("\n") # or txt.extract() to completely remove it

print(soup)

Prints:

<!DOCTYPE html>

<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
Related