crawl4ai icon indicating copy to clipboard operation
crawl4ai copied to clipboard

fix: preserve tail text when remove_empty_elements_fast removes an element

Open devteamaegis opened this issue 6 months ago • 0 comments

Problem

remove_empty_elements_fast() calls parent.remove(el) to discard low-word-count elements. In lxml, el.tail stores the text that follows an element in the parent's serialised output — this text is silently discarded when the element is removed.

Minimal reproduction:

from lxml import html as lhtml
root = lhtml.fragment_fromstring("<div><span></span>trailing text</div>")
# ... call remove_empty_elements_fast ...
print(lhtml.tostring(root, encoding="unicode"))
# Was: <div></div>   — "trailing text" lost
# Fix: <div>trailing text</div>

Reported in #1938.

Fix

Before calling parent.remove(el), rescue el.tail:

tail = el.tail
if tail:
    prev = el.getprevious()
    if prev is not None:
        prev.tail = (prev.tail or "") + tail
    else:
        parent.text = (parent.text or "") + tail
parent.remove(el)

This pattern is already used in the same file when stripping <script> and <style> elements (lines 734–747).

Tests

Three new regression tests in tests/unit/test_remove_empty_elements_tail.py:

Test Scenario
test_tail_after_removed_element_is_preserved Basic tail text survives
test_tail_appended_to_previous_sibling Tail appended to prior sibling's tail
test_tail_merged_into_parent_text_when_first_child Tail merged into parent text when no prior sibling

All three pass with the fix applied and fail on main.

devteamaegis avatar May 28 '26 16:05 devteamaegis