Skillversitas

Modifying the Parse Tree

Beautiful Soup trees are mutable. You can change tag names, edit attributes, replace text, insert new nodes, and restructure the document before serializing it back to HTML. This makes the library a lightweight HTML transformer, not just an extractor.

Change a Tag Name

from bs4 import BeautifulSoup

soup = BeautifulSoup("<blink>wow</blink>", "html.parser")
soup.blink.name = "strong"
print(soup)  # <strong>wow</strong>

Edit Attributes

soup = BeautifulSoup("<a href="old">link</a>", "html.parser")
a = soup.a
a["href"] = "https://new.example.com"   # update
a["class"] = ["external", "btn"]        # set a class list
a["data-x"] = "1"                       # add
del a["data-x"]                          # remove
print(soup)

Change Text

soup = BeautifulSoup("<p>old text</p>", "html.parser")
soup.p.string = "new text"
print(soup)  # <p>new text</p>

If the tag has multiple children, .string is None; use .clear() first or replace the tag's contents explicitly.

The Modification Methods

The full toolkit is covered in the next chapters:

  • insert / insert_before / insert_after - add nodes around an existing one.
  • replace_with / unwrap / wrap - swap a tag for another, or shed or add a wrapper.
  • extract / decompose / clear - remove nodes from the tree, with or without garbage collection.
  • new_tag / new_string - create fresh tags and strings to insert.

Summary

The parse tree is a living document: rename tags by assigning .name, edit .attrs like a dict, and set .string to replace a tag's text. The insert, replace, unwrap, wrap, extract, decompose, and clear methods (covered next) let you restructure documents and write the result back as clean HTML.