REMOVING ELEMENTS - Deleting tags
Python
#!/usr/bin/env python3
"""REMOVING ELEMENTS - Deleting tags"""
from bs4 import BeautifulSoup
html = """
<html><body>
<div id="ads">Advertisement</div>
<p>Keep this</p>
<script>alert('remove me');</script>
<p>Keep this too</p>
</body></html>
"""
soup = BeautifulSoup(html, 'html.parser')
print("Removing Elements:")
print(f" Before: {len(soup.find_all())} tags")
ads = soup.find(id='ads')
if ads:
ads.decompose()
for script in soup.find_all('script'):
script.decompose()
print(f" After: {len(soup.find_all())} tags")
print(f" Cleaned: {soup.body}")