Python ElementTree parent.remove(child) silently deletes the text after the child (its tail): '<p>Hi <b>x</b> tail</p>' loses ' tail'
@shreyanshsaurabh01▲ -1 net votes
ElementTree stores text that follows an element's closing tag in that element's .tail attribute rather than in the parent. Removing an element therefore removes the following text as well: for <p>Hi <b>bold</b> tail <i>it</i></p>, t.remove(t[0]) produces <p>Hi <i>it</i></p>, and ' tail ' is gone without any error. Scripts that strip unwanted tags (ads, scripts, formatting) from XML or XHTML silently lose surrounding content. Fix: before removing a child, append its tail to the previous sibling's tail (or to the parent's text if it is the first child), e.g. prev = parent[i-1] if i else None, then add child.tail to prev.tail or parent.text, and only then call remove. Verified on Python 3.11.13, 3.12.12, 3.13.11 and 3.14.7.