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(deep-crawl): count queued next-level URLs against max_pages in BFS (#2338)

drakeo338860072e6fda9
diff --git a/crawl4ai/deep_crawling/bfs_strategy.py b/crawl4ai/deep_crawling/bfs_strategy.py
index 2b00a6cd..8353038c 100644
--- a/crawl4ai/deep_crawling/bfs_strategy.py
+++ b/crawl4ai/deep_crawling/bfs_strategy.py
@@ -150,7 +150,7 @@ class BFSDeepCrawlStrategy(DeepCrawlStrategy):
return
# If we've reached the max pages limit, don't discover new links
- remaining_capacity = self.max_pages - self._pages_crawled
+ remaining_capacity = self.max_pages - self._pages_crawled - len(next_level)
if remaining_capacity <= 0:
self.logger.info(f"Max pages limit ({self.max_pages}) reached, stopping link discovery")
return
diff --git a/tests/deep_crawling/test_bfs_max_pages_next_level.py b/tests/deep_crawling/test_bfs_max_pages_next_level.py
new file mode 100644
index 00000000..edd6497d
--- /dev/null
+++ b/tests/deep_crawling/test_bfs_max_pages_next_level.py
@@ -0,0 +1,30 @@
+"""max_pages must count URLs already queued for the next level (#2338)."""
+
+import pytest
+
+from crawl4ai.deep_crawling import BFSDeepCrawlStrategy
+from crawl4ai.models import CrawlResult
+
+
+def _result(url, links):
+ r = CrawlResult(url=url, html="", success=True)
+ r.links = {"internal": [{"href": h} for h in links], "external": []}
+ return r
+
+
+async def test_link_discovery_budget_counts_next_level():
+ strategy = BFSDeepCrawlStrategy(max_depth=2, max_pages=50)
+ strategy._pages_crawled = 36 # 14 pages of budget left
+
+ visited = set()
+ next_level = []
+ depths = {}
+ for p in range(35):
+ parent = f"https://example.com/p{p}"
+ links = [f"https://example.com/p{p}/c{i}" for i in range(30)]
+ await strategy.link_discovery(
+ _result(parent, links), parent, 1, visited, next_level, depths
+ )
+
+ assert len(next_level) == 14