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: ignore <noscript> text inside script, style and comments when counting tags

ntohidib59dc9c721b4
diff --git a/crawl4ai/content_scraping_strategy.py b/crawl4ai/content_scraping_strategy.py
index 8b8b07e1..31059191 100644
--- a/crawl4ai/content_scraping_strategy.py
+++ b/crawl4ai/content_scraping_strategy.py
@@ -38,6 +38,10 @@ TWITTER_REGEX = re.compile(r"^twitter:")
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*>|<!--.*?-->",
+ re.IGNORECASE | re.DOTALL,
+)
def unwrap_orphaned_noscript(html: str) -> str:
@@ -51,10 +55,12 @@ def unwrap_orphaned_noscript(html: str) -> str:
removal below then deletes the whole page.
Unbalanced tag counts identify that serialization damage, so well-formed
- documents are returned untouched.
+ documents are returned untouched. Tags inside <script>, <style> and
+ comments are only text, so they are left out of the count.
"""
- opens = len(NOSCRIPT_OPEN_REGEX.findall(html))
- closes = len(NOSCRIPT_CLOSE_REGEX.findall(html))
+ markup = RAW_TEXT_REGEX.sub("", html)
+ opens = len(NOSCRIPT_OPEN_REGEX.findall(markup))
+ closes = len(NOSCRIPT_CLOSE_REGEX.findall(markup))
if opens <= closes:
return html
return NOSCRIPT_CLOSE_REGEX.sub("", NOSCRIPT_OPEN_REGEX.sub("", html))
diff --git a/tests/test_unclosed_noscript.py b/tests/test_unclosed_noscript.py
index 57d1d15d..66236722 100644
--- a/tests/test_unclosed_noscript.py
+++ b/tests/test_unclosed_noscript.py
@@ -75,3 +75,26 @@ def test_fit_html_keeps_body_nested_in_unclosed_noscript():
fit_html = preprocess_html_for_schema(DAMAGED_CAPTURE, text_threshold=500, max_size=300_000)
assert "Unstunned. Hand slaughtered. Halal certified." in fit_html
+
+
+ "decoy",
+ [
+ '<script>const sample = "<noscript>";</script>',
+ "<style>/* <noscript> */</style>",
+ "<!-- <noscript> -->",
+ ],
+)
+def test_noscript_text_in_script_style_or_comment_is_not_counted(strategy, decoy):
+ html = (
+ "<html><body>"
+ f"{decoy}"
+ "<noscript>Please enable JavaScript</noscript>"
+ "<h1>Real heading</h1>"
+ "</body></html>"
+ )
+
+ result = strategy.scrap("https://example.com/", html)
+
+ assert "Please enable JavaScript" not in result.cleaned_html
+ assert "Real heading" in result.cleaned_html