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(crawler): make the visibility warning survive verbose=False

ntohidi1bac351fa389
diff --git a/crawl4ai/async_crawler_strategy.py b/crawl4ai/async_crawler_strategy.py
index d904ba81..6d0fb476 100644
--- a/crawl4ai/async_crawler_strategy.py
+++ b/crawl4ai/async_crawler_strategy.py
@@ -812,6 +812,7 @@ class AsyncPlaywrightCrawlerStrategy(AsyncCrawlerStrategy):
await page.wait_for_selector("body", state="attached", timeout=30000)
# Use the new check_visibility function with csp_compliant_wait
+ _visibility_wait_start = time.perf_counter()
is_visible = await self.csp_compliant_wait(
page,
"""() => {
@@ -826,19 +827,33 @@ class AsyncPlaywrightCrawlerStrategy(AsyncCrawlerStrategy):
timeout=config.body_visibility_timeout,
)
- if not is_visible and config.ignore_body_visibility:
- # The wait timed out and its result is about to be discarded,
- # so the crawl still succeeds — just body_visibility_timeout ms
- # slower. Say so, otherwise the delay is invisible (see #2144).
+ _visibility_wait_ms = (
+ time.perf_counter() - _visibility_wait_start
+ ) * 1000
+
+ # csp_compliant_wait also returns False when the evaluation itself
+ # fails (page closed, context destroyed by a redirect), which costs
+ # no time — only warn about a wait that actually burned its budget.
+ if (
+ not is_visible
+ and config.ignore_body_visibility
+ and _visibility_wait_ms >= config.body_visibility_timeout * 0.9
+ ):
+ # The wait timed out and its result is about to be discarded, so
+ # the crawl still succeeds — just this much slower, on every crawl
+ # of this page. force_verbose because the whole point is that the
+ # delay is otherwise invisible, and the servers and batch jobs that
+ # most need to see it run with verbose off (see #2144).
self.logger.warning(
message=(
- "Body never became visible after {timeout}ms — the page may "
+ "Body never became visible after {elapsed}ms — the page may "
"use ng-cloak/v-cloak. This delay is added to every crawl of "
"this page; lower CrawlerRunConfig.body_visibility_timeout "
"to shorten it."
),
tag="WARNING",
- params={"timeout": config.body_visibility_timeout},
+ params={"elapsed": round(_visibility_wait_ms)},
+ force_verbose=True,
)
if not is_visible and not config.ignore_body_visibility:
diff --git a/tests/test_body_visibility_warning.py b/tests/test_body_visibility_warning.py
index 29e8a289..7f967665 100644
--- a/tests/test_body_visibility_warning.py
+++ b/tests/test_body_visibility_warning.py
@@ -7,6 +7,7 @@ impossible to attribute without instrumenting the pipeline, and what makes
`body_visibility_timeout` undiscoverable. A warning names the option.
"""
+import asyncio
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
@@ -16,8 +17,9 @@ from crawl4ai.async_configs import CrawlerRunConfig
from crawl4ai.async_crawler_strategy import AsyncPlaywrightCrawlerStrategy
-def _strategy(is_visible: bool):
- """A strategy whose body-visibility wait returns `is_visible`."""
+def _strategy(is_visible: bool, wait_seconds: float = 0.0):
+ """A strategy whose body-visibility wait returns `is_visible` after
+ `wait_seconds` of (real) waiting."""
page = MagicMock()
page.evaluate = AsyncMock()
page.set_content = AsyncMock()
@@ -32,34 +34,71 @@ def _strategy(is_visible: bool):
get_page=AsyncMock(return_value=(page, MagicMock()))
)
strategy.execute_hook = AsyncMock()
- strategy.csp_compliant_wait = AsyncMock(return_value=is_visible)
+
+ async def wait(*args, **kwargs):
+ await asyncio.sleep(wait_seconds)
+ return is_visible
+
+ strategy.csp_compliant_wait = AsyncMock(side_effect=wait)
strategy.check_visibility = AsyncMock(return_value={})
strategy.logger = MagicMock()
return strategy
-def _warnings(strategy):
+def _visibility_warnings(strategy):
+ """The body-visibility warning calls, selected by message rather than by
+ position — other warnings may fire on the same crawl."""
return [
- call.kwargs.get("message", "")
+ call
for call in strategy.logger.warning.call_args_list
+ if "never became visible" in call.kwargs.get("message", "")
]
@pytest.mark.asyncio
async def test_warns_when_wait_times_out_and_result_is_discarded():
- strategy = _strategy(is_visible=False)
+ strategy = _strategy(is_visible=False, wait_seconds=0.1)
+ config = CrawlerRunConfig(session_id="body-vis-warn", body_visibility_timeout=100)
+
+ await strategy._crawl_web("raw:<body>hi</body>", config)
+
+ calls = _visibility_warnings(strategy)
+ assert len(calls) == 1, strategy.logger.warning.call_args_list
+ assert "body_visibility_timeout" in calls[0].kwargs["message"]
+ # The time actually spent is reported, so the number matches the delay the
+ # user is trying to explain.
+ assert calls[0].kwargs["params"]["elapsed"] >= 90
+
+
+async def test_warning_is_not_suppressed_by_verbose_off():
+ """Servers and batch jobs run with verbose off — the case that most needs
+ this warning. Without force_verbose the logger drops it (#2144)."""
+ strategy = _strategy(is_visible=False, wait_seconds=0.1)
+ config = CrawlerRunConfig(
+ session_id="body-vis-quiet-logger", body_visibility_timeout=100, verbose=False
+ )
+
+ await strategy._crawl_web("raw:<body>hi</body>", config)
+
+ calls = _visibility_warnings(strategy)
+ assert len(calls) == 1
+ assert calls[0].kwargs.get("force_verbose") is True
+
+
+async def test_no_warning_when_wait_fails_early():
+ """csp_compliant_wait also returns False when the evaluation errors out
+ (page closed, context destroyed) — that costs no time, so blaming
+ body_visibility_timeout for it would send the user after the wrong knob."""
+ strategy = _strategy(is_visible=False, wait_seconds=0.0)
config = CrawlerRunConfig(
- session_id="body-vis-warn", body_visibility_timeout=1234
+ session_id="body-vis-early-fail", body_visibility_timeout=30000
)
await strategy._crawl_web("raw:<body>hi</body>", config)
- messages = _warnings(strategy)
- assert any("never became visible" in m for m in messages), messages
- assert any("body_visibility_timeout" in m for m in messages), messages
- # The timeout that actually applied is reported, not the hardcoded default.
- params = strategy.logger.warning.call_args.kwargs["params"]
- assert params["timeout"] == 1234
+ assert _visibility_warnings(strategy) == []
@pytest.mark.asyncio
@@ -69,7 +108,7 @@ async def test_no_warning_when_body_is_visible():
await strategy._crawl_web("raw:<body>hi</body>", config)
- assert not any("never became visible" in m for m in _warnings(strategy))
+ assert _visibility_warnings(strategy) == []
@pytest.mark.asyncio
@@ -86,4 +125,4 @@ async def test_no_warning_when_hidden_body_is_treated_as_an_error():
with pytest.raises(Error, match="Body element is hidden"):
await strategy._crawl_web("raw:<body>hi</body>", config)
- assert not any("never became visible" in m for m in _warnings(strategy))
+ assert _visibility_warnings(strategy) == []