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: keep the raw-text strip linear on unclosed script, style and comments

ntohidi344270798764
diff --git a/crawl4ai/content_scraping_strategy.py b/crawl4ai/content_scraping_strategy.py
index 31059191..acb19029 100644
--- a/crawl4ai/content_scraping_strategy.py
+++ b/crawl4ai/content_scraping_strategy.py
@@ -39,7 +39,7 @@ DIMENSION_REGEX = re.compile(r"(\d+)(\D*)")
NOSCRIPT_OPEN_REGEX = re.compile(r"<noscript\b[^>]*>", re.IGNORECASE)
NOSCRIPT_CLOSE_REGEX = re.compile(r"</noscript\s*>", re.IGNORECASE)
RAW_TEXT_REGEX = re.compile(
- r"<script\b.*?</script\s*>|<style\b.*?</style\s*>|<!--.*?-->",
+ r"<script\b.*?(?:</script\s*>|\Z)|<style\b.*?(?:</style\s*>|\Z)|<!--.*?(?:-->|\Z)",
re.IGNORECASE | re.DOTALL,
)
@@ -56,7 +56,9 @@ def unwrap_orphaned_noscript(html: str) -> str:
Unbalanced tag counts identify that serialization damage, so well-formed
documents are returned untouched. Tags inside <script>, <style> and
- comments are only text, so they are left out of the count.
+ comments are only text, so they are left out of the count. An unclosed
+ one runs to the end of the document, as in a browser, which also keeps
+ the scan linear on pages with many unclosed openers.
"""
markup = RAW_TEXT_REGEX.sub("", html)
opens = len(NOSCRIPT_OPEN_REGEX.findall(markup))
diff --git a/tests/test_unclosed_noscript.py b/tests/test_unclosed_noscript.py
index 66236722..27e09681 100644
--- a/tests/test_unclosed_noscript.py
+++ b/tests/test_unclosed_noscript.py
@@ -98,3 +98,16 @@ def test_noscript_text_in_script_style_or_comment_is_not_counted(strategy, decoy
assert "Please enable JavaScript" not in result.cleaned_html
assert "Real heading" in result.cleaned_html
+
+
[email protected]("opener", ["<!--", "<script>", "<style>"])
+def test_many_unclosed_raw_text_openers_stay_fast(opener):
+ import time
+
+ html = (opener + "a" * 42) * 20_000 # about 1 MB
+
+ start = time.time()
+ unwrap_orphaned_noscript(html)
+
+ # Quadratic matching took over a minute here; linear takes milliseconds.
+ assert time.time() - start < 2