Skip to content

Official Crawl4AI Cloud: a hosted web scraping, extraction, and search API for AI agents. Free API key, 1,000 credits a month, no card. Fully open source: this repo is the Apache-2.0 crawler that powers it, and you can self-host it.

fix(scraping): keep a space where a whitespace-only element is removed

drakeo338c381413f0914
diff --git a/crawl4ai/content_scraping_strategy.py b/crawl4ai/content_scraping_strategy.py
index 8b8b07e1..d9ecfd86 100644
--- a/crawl4ai/content_scraping_strategy.py
+++ b/crawl4ai/content_scraping_strategy.py
@@ -586,6 +586,10 @@ class LXMLWebScrapingStrategy(ContentScrapingStrategy):
if parent is not None:
# Preserve .tail text before removing the element
tail = el.tail
+ if el.text and not text_content:
+ # A whitespace-only element separates the words around
+ # it, so keep one space where it was.
+ tail = " " + (tail or "")
if tail:
prev = el.getprevious()
if prev is not None:
diff --git a/tests/test_issue_2328_inline_whitespace.py b/tests/test_issue_2328_inline_whitespace.py
new file mode 100644
index 00000000..65997587
--- /dev/null
+++ b/tests/test_issue_2328_inline_whitespace.py
@@ -0,0 +1,38 @@
+"""
+Tests for issue #2328: whitespace-only inline elements removed from
+cleaned_html, merging words in raw_markdown.
+"""
+
+import pytest
+from crawl4ai.content_scraping_strategy import LXMLWebScrapingStrategy
+from crawl4ai.markdown_generation_strategy import DefaultMarkdownGenerator
+
+
+def strategy():
+ return LXMLWebScrapingStrategy()
+
+
+SPLIT_HTML = (
+ "<html><body><p><span>H</span><span>i</span><span> </span>"
+ "<span>t</span><span>h</span><span>e</span><span>r</span><span>e</span></p>"
+ "<p>plain text stays fine</p></body></html>"
+)
+
+
+def test_whitespace_span_between_words_is_kept_in_markdown(strategy):
+ result = strategy._scrap("http://test.com", SPLIT_HTML)
+ md = DefaultMarkdownGenerator().generate_markdown(
+ input_html=result["cleaned_html"], base_url="http://test.com"
+ )
+ assert "Hi there" in md.raw_markdown
+ assert "plain text stays fine" in md.raw_markdown
+
+
+def test_whitespace_spans_between_several_words(strategy):
+ html = "<html><body><p><span>one</span><span> </span><span>two</span><span> </span><span>three</span></p></body></html>"
+ result = strategy._scrap("http://test.com", html)
+ md = DefaultMarkdownGenerator().generate_markdown(
+ input_html=result["cleaned_html"], base_url="http://test.com"
+ )
+ assert "one two three" in md.raw_markdown