Modify the tree

decompose, extract, and replace_with.

Beautiful Soup can change the tree in memory. decompose() removes a tag and its children. extract() removes it and returns it. replace_with swaps a node.

Goal

Drop a sold-out item, then replace a heading.

decompose

html = """
<ul>
  <li class="item">Chai</li>
  <li class="item sold-out">Samosa</li>
  <li class="item">Mandazi</li>
</ul>
"""
soup = BeautifulSoup(html, "html.parser")
gone = soup.select_one("li.sold-out")
gone.decompose()
print([li.get_text() for li in soup.find_all("li")])

replace_with

html = "<h1>Old title</h1>"
soup = BeautifulSoup(html, "html.parser")
soup.h1.string.replace_with("Nairobi kiosk")
print(soup.h1)

Changes are only in this soup object. They are not written to disk until you open(..., "w") or print str(soup) into a file (Export chapter).

Pitfall

After decompose(), do not use that tag again. extract() is the right call if you still need the node.