Skillversitas

Creating and Removing Tags

Beautiful Soup can build tags and strings from scratch through the soup object: .new_tag() creates a Tag with a name and optional attributes, and .new_string() creates a NavigableString. Combined with the insert, wrap, and remove methods, this is how you generate HTML programmatically.

.new_tag(name, attrs)

from bs4 import BeautifulSoup

soup = BeautifulSoup("", "html.parser")
div = soup.new_tag("div", class_="box", id="b1")
print(div)  # <div class="box" id="b1"></div>

.new_string(text)

text = soup.new_string("hello")
div.append(text)
print(div)  # <div class="box" id="b1">hello</div>

Building Small Documents

soup = BeautifulSoup("", "html.parser")
body = soup.new_tag("body")
h1 = soup.new_tag("h1")
h1.string = "Report"
p = soup.new_tag("p")
p.string = "Generated at runtime."
body.append(h1)
body.append(p)
soup.append(body)
print(soup.prettify())

Removal Recap

Removing is the mirror image: extract() removes a node and keeps it, decompose() removes and frees it, and clear() empties a tag's children. A typical clean-up-and-rebuild sequence:

soup = BeautifulSoup("<div><span>old</span></div>", "html.parser")
old = soup.span.extract()
new_span = soup.new_tag("span")
new_span.string = "new"
soup.div.insert(0, new_span)
print(soup)  # <div><span>new</span></div>

Summary

Use soup.new_tag() and soup.new_string() to create fresh elements, append or insert them to build documents, and pair them with extract, decompose, or clear to remove or reset content. Remember that a created tag stays detached until you attach it with append or insert, and that new strings and new tags together let you generate whole fragments of HTML without ever touching a source file. This create-and-remove toolkit is all you need to generate or transform HTML in pure Python.