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.
Python aiai-agentscrawl4ai-cloudcrawlerdata-extractionllmmarkdownmcpopen-sourceplaywrightpythonragscraperweb-crawlerweb-crawlingweb-scraping
fix(tables): clamp colspan and rowspan so one cell cannot hang the parse
ntohidiee1a295394a0
diff --git a/crawl4ai/table_extraction.py b/crawl4ai/table_extraction.pyindex 2379872f..8440cadf 100644--- a/crawl4ai/table_extraction.py+++ b/crawl4ai/table_extraction.py@@ -210,8 +210,11 @@ class DefaultTableExtraction(TableExtractionStrategy):threshold = kwargs.get("table_score_threshold", self.table_score_threshold)return score >= threshold- @staticmethod- def _build_grid(rows: List[etree.Element]) -> List[List[str]]:+ # HTML Standard caps colspan at 1000; browsers clamp to the same value.+ COLSPAN_LIMIT = 1000++ @classmethod+ def _build_grid(cls, rows: List[etree.Element]) -> List[List[str]]:"""Lay <tr> cells into a rectangular grid, honouring colspan/rowspan.Each cell writes its text into every slot of the rectangle it spans,@@ -221,9 +224,14 @@ class DefaultTableExtraction(TableExtractionStrategy):"""grid: List[List[str]] = [[] for _ in rows]+ def span(value, limit: int) -> int:+ """Read a span attribute the way a browser does: junk counts as 1."""+ try:+ return min(max(int(value), 1), limit)+ except (TypeError, ValueError):+ return 1+def put(r: int, c: int, text: str) -> None:- if r >= len(grid): # rowspan reaching past the last row- returnrow = grid[r]row.extend([None] * (c + 1 - len(row)))row[c] = text@@ -234,8 +242,13 @@ class DefaultTableExtraction(TableExtractionStrategy):while c < len(grid[r]) and grid[r][c] is not None:c += 1 # slot already taken by a rowspan from abovetext = cell.text_content().strip()- colspan = max(int(cell.get("colspan") or 1), 1)- rowspan = max(int(cell.get("rowspan") or 1), 1)+ # Both spans are clamped, so one crafted cell cannot make the+ # work explode: scraped HTML is untrusted, and rowspan*colspan+ # is a product. COLSPAN_LIMIT is the HTML Standard's cap, which+ # is what browsers apply; a rowspan cannot reach past the last+ # row, which is a tighter bound than the standard's 65534.+ colspan = span(cell.get("colspan"), cls.COLSPAN_LIMIT)+ rowspan = span(cell.get("rowspan"), len(grid) - r)for dr in range(rowspan):for dc in range(colspan):put(r + dr, c + dc, text)diff --git a/tests/test_table_rowspan_grid.py b/tests/test_table_rowspan_grid.pyindex a54724da..35125a4b 100644--- a/tests/test_table_rowspan_grid.py+++ b/tests/test_table_rowspan_grid.py@@ -7,6 +7,8 @@ ignored entirely, so a spanning value never reached the rows it covers.https://github.com/unclecode/crawl4ai/issues/2258"""+import time+from lxml import html as lhtmlfrom crawl4ai import DefaultTableExtraction@@ -121,3 +123,40 @@ def test_key_value_first_row_is_not_mistaken_for_a_header():<tr><th scope="row">Drink</th><td>Apple cider</td></tr></table>""")assert tables[0]["rows"] == [["Food", "Apple pie"], ["Drink", "Apple cider"]]+++def test_absurd_spans_are_clamped_instead_of_exploding():+ """rowspan * colspan is a product, and scraped HTML is untrusted.++ One crafted cell must not be able to hang the crawl. rowspan is bounded by+ the rows that exist, colspan by the HTML Standard's cap.+ """+ html = """+ <table>+ <thead><tr><th>A</th><th>B</th></tr></thead>+ <tbody>+ <tr><td rowspan="1000000" colspan="1000000">X</td><td>b1</td></tr>+ <tr><td>c1</td><td>c2</td></tr>+ </tbody></table>"""+ started = time.perf_counter()+ tables = _extract(html)+ elapsed = time.perf_counter() - started++ assert elapsed < 2, f"clamping regressed: took {elapsed:.1f}s"+ rows = tables[0]["rows"]+ assert len(rows) == 2, "rowspan must not invent rows beyond the table"+ limit = DefaultTableExtraction.COLSPAN_LIMIT+ assert all(len(row) <= limit for row in rows), "colspan must be capped"+++def test_invalid_span_attribute_counts_as_one():+ """Browsers treat junk spans as 1; parsing must not raise on them."""+ tables = _extract("""+ <table>+ <thead><tr><th>A</th><th>B</th></tr></thead>+ <tbody>+ <tr><td colspan="100%">a</td><td>b</td></tr>+ <tr><td rowspan="lots">c</td><td>d</td></tr>+ <tr><td colspan="-3">e</td><td>f</td></tr>+ </tbody></table>""")+ assert tables[0]["rows"] == [["a", "b"], ["c", "d"], ["e", "f"]]