Skip to content

CREATING NEW ELEMENTS - Building HTML

Python
#!/usr/bin/env python3
"""CREATING NEW ELEMENTS - Building HTML"""
from bs4 import BeautifulSoup
soup = BeautifulSoup("<html><body></body></html>", 'html.parser')
print("Creating Elements:")
new_tag = soup.new_tag("p")
new_tag.string = "New paragraph"
new_tag['class'] = 'created'
soup.body.append(new_tag)
print(f"  Created: {new_tag}")
new_div = soup.new_tag("div", id="container")
new_div.string = "Container content"
soup.body.insert(0, new_div)
print(f"  Inserted: {new_div}")
print(f"  Final HTML: {soup.body}")