From da3e5b1d0235fd8df73f3cb11225d6935439c9c6 Mon Sep 17 00:00:00 2001 From: chalakbilla Date: Thu, 12 Nov 2026 02:01:57 +0530 Subject: [PATCH 1/4] fix(adaptive-crawler): do not train rendering type predictor on transient static failure --- .../_adaptive_playwright_crawler.py | 39 +++- .../test_adaptive_playwright_crawler.py | 194 +++++++++++++++++- 2 files changed, 227 insertions(+), 6 deletions(-) diff --git a/src/crawlee/crawlers/_adaptive_playwright/_adaptive_playwright_crawler.py b/src/crawlee/crawlers/_adaptive_playwright/_adaptive_playwright_crawler.py index 9f498f0b13..feacfe9555 100644 --- a/src/crawlee/crawlers/_adaptive_playwright/_adaptive_playwright_crawler.py +++ b/src/crawlee/crawlers/_adaptive_playwright/_adaptive_playwright_crawler.py @@ -1,5 +1,6 @@ from __future__ import annotations +import asyncio import logging from collections.abc import Awaitable, Callable, Coroutine from copy import deepcopy @@ -30,7 +31,13 @@ from crawlee.crawlers._beautifulsoup._beautifulsoup_parser import BeautifulSoupParser from crawlee.crawlers._parsel._parsel_parser import ParselParser from crawlee.crawlers._playwright._playwright_crawler import _PlaywrightCrawlerAdditionalOptions -from crawlee.errors import ContextPipelineInitializationError, RequestHandlerError, RequestThrottledError +from crawlee.errors import ( + ContextPipelineInitializationError, + ProxyError, + RequestHandlerError, + RequestThrottledError, + SessionError, +) from crawlee.statistics import Statistics, StatisticsState from ._adaptive_playwright_crawler_statistics import AdaptivePlaywrightCrawlerStatisticState @@ -52,6 +59,16 @@ from crawlee.crawlers._basic._basic_crawler import _BasicCrawlerOptions +# Infrastructure errors during static sub-crawler runs that do not indicate whether a page requires +# client-side rendering. +_TRANSIENT_STATIC_ERRORS: tuple[type[BaseException], ...] = ( + SessionError, + ProxyError, + ConnectionError, + TimeoutError, + asyncio.TimeoutError, +) + TStaticParseResult = TypeVar('TStaticParseResult') TStaticSelectResult = TypeVar('TStaticSelectResult') TStaticCrawlingContext = TypeVar('TStaticCrawlingContext', bound=ParsedHttpCrawlingContext) @@ -435,15 +452,27 @@ async def use_initial_state_copy( if pw_run.result: if should_detect_rendering_type: - detection_result: RenderingType + detection_result: RenderingType | None static_run = await self._crawl_one('static', context=context, use_state=use_initial_state_copy) - if static_run.result and self.result_comparator(static_run.result, pw_run.result): + + static_exception = static_run.exception + if isinstance(static_exception, (ContextPipelineInitializationError, RequestHandlerError)): + static_exception = static_exception.wrapped_exception + + if static_exception is not None and isinstance(static_exception, _TRANSIENT_STATIC_ERRORS): + context.log.debug( + f'Static run failed with {type(static_exception).__name__}; ' + f'skipping rendering type detection result for {context.request.url}.' + ) + detection_result = None + elif static_run.result and self.result_comparator(static_run.result, pw_run.result): detection_result = 'static' else: detection_result = 'client only' - context.log.debug(f'Detected rendering type {detection_result} for {context.request.url}') - self.rendering_type_predictor.store_result(context.request, detection_result) + if detection_result is not None: + context.log.debug(f'Detected rendering type {detection_result} for {context.request.url}') + self.rendering_type_predictor.store_result(context.request, detection_result) self._context_result_map[context] = pw_run.result diff --git a/tests/unit/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py b/tests/unit/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py index 04141c49c1..608da44d30 100644 --- a/tests/unit/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py +++ b/tests/unit/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py @@ -1,10 +1,43 @@ from __future__ import annotations +import asyncio +import logging import sys -from unittest.mock import patch +from typing import TYPE_CHECKING +from unittest.mock import AsyncMock, Mock, patch import pytest +from crawlee._request import Request +from crawlee._types import BasicCrawlingContext, RequestHandlerRunResult +from crawlee.crawlers import ( + AdaptivePlaywrightCrawler, + RenderingType, + RenderingTypePrediction, + RenderingTypePredictor, +) +from crawlee.crawlers._adaptive_playwright._adaptive_playwright_crawler import SubCrawlerRun +from crawlee.errors import ContextPipelineInitializationError, ProxyError, RequestHandlerError, SessionError + +if TYPE_CHECKING: + from crawlee._types import UseStateFunction + + +@pytest.fixture +def crawling_context() -> BasicCrawlingContext: + return BasicCrawlingContext( + request=Request.from_url(url='https://example.com/test'), + session=Mock(), + proxy_info=Mock(), + send_request=AsyncMock(), + add_requests=AsyncMock(), + push_data=AsyncMock(), + get_key_value_store=AsyncMock(), + use_state=AsyncMock(return_value={}), + log=logging.getLogger('test'), + register_deferred_cleanup=lambda _: None, + ) + @pytest.mark.parametrize( 'optional_module_name', @@ -31,3 +64,162 @@ def test_import_error_handled(optional_module_name: str) -> None: with pytest.raises(ImportError): from crawlee.crawlers import AdaptivePlaywrightCrawler # noqa: F401 PLC0415 + + +@pytest.mark.parametrize( + 'transient_exception', + [ + pytest.param(SessionError('Session blocked'), id='session-error'), + pytest.param(ProxyError('Proxy connection failed'), id='proxy-error'), + pytest.param(ConnectionResetError('Connection reset by peer'), id='connection-error'), + pytest.param(TimeoutError('Request timed out'), id='timeout-error'), + pytest.param(asyncio.TimeoutError('Asyncio timeout'), id='asyncio-timeout-error'), + pytest.param( + ContextPipelineInitializationError( + ConnectionResetError('Connection reset by peer'), + Mock(spec=BasicCrawlingContext), + ), + id='pipeline-initialization-connection-error', + ), + ], +) +async def test_transient_failure_skips_rendering_type_detection( + transient_exception: Exception, + crawling_context: BasicCrawlingContext, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A transient infrastructure error in the static sub-crawler skips training the predictor.""" + predictor = Mock(spec=RenderingTypePredictor) + predictor.predict.return_value = RenderingTypePrediction( + rendering_type='client only', detection_probability_recommendation=1.0 + ) + crawler = AdaptivePlaywrightCrawler.with_beautifulsoup_static_parser(rendering_type_predictor=predictor) + + pw_result = RequestHandlerRunResult(key_value_store_getter=AsyncMock()) + + async def mock_crawl_one( + rendering_type: RenderingType, + context: BasicCrawlingContext, # noqa: ARG001 + use_state: UseStateFunction | None = None, # noqa: ARG001 + ) -> SubCrawlerRun: + if rendering_type == 'client only': + return SubCrawlerRun(result=pw_result) + return SubCrawlerRun(exception=transient_exception) + + monkeypatch.setattr(crawler, '_crawl_one', mock_crawl_one) + + async with crawler.statistics: + await crawler._run_request_handler(crawling_context) + + predictor.store_result.assert_not_called() + + +@pytest.mark.parametrize( + 'handler_exception', + [ + pytest.param(AttributeError("'NoneType' object has no attribute 'text'"), id='attribute-error'), + pytest.param(KeyError('price'), id='key-error'), + pytest.param( + RequestHandlerError( + AttributeError("'NoneType' object has no attribute 'text'"), + Mock(spec=BasicCrawlingContext), + ), + id='request-handler-error', + ), + ], +) +async def test_handler_error_labels_client_only( + handler_exception: Exception, + crawling_context: BasicCrawlingContext, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A handler error in the static sub-crawler trains the predictor with 'client only'.""" + predictor = Mock(spec=RenderingTypePredictor) + predictor.predict.return_value = RenderingTypePrediction( + rendering_type='client only', detection_probability_recommendation=1.0 + ) + crawler = AdaptivePlaywrightCrawler.with_beautifulsoup_static_parser(rendering_type_predictor=predictor) + + pw_result = RequestHandlerRunResult(key_value_store_getter=AsyncMock()) + + async def mock_crawl_one( + rendering_type: RenderingType, + context: BasicCrawlingContext, # noqa: ARG001 + use_state: UseStateFunction | None = None, # noqa: ARG001 + ) -> SubCrawlerRun: + if rendering_type == 'client only': + return SubCrawlerRun(result=pw_result) + return SubCrawlerRun(exception=handler_exception) + + monkeypatch.setattr(crawler, '_crawl_one', mock_crawl_one) + + async with crawler.statistics: + await crawler._run_request_handler(crawling_context) + + predictor.store_result.assert_called_once_with(crawling_context.request, 'client only') + + +async def test_static_success_matching_browser_labels_static( + crawling_context: BasicCrawlingContext, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A successful static sub-crawler run matching the browser run trains the predictor with 'static'.""" + predictor = Mock(spec=RenderingTypePredictor) + predictor.predict.return_value = RenderingTypePrediction( + rendering_type='client only', detection_probability_recommendation=1.0 + ) + crawler = AdaptivePlaywrightCrawler.with_beautifulsoup_static_parser(rendering_type_predictor=predictor) + + pw_result = RequestHandlerRunResult(key_value_store_getter=AsyncMock()) + await pw_result.push_data({'data': 'foo'}) + static_result = RequestHandlerRunResult(key_value_store_getter=AsyncMock()) + await static_result.push_data({'data': 'foo'}) + + async def mock_crawl_one( + rendering_type: RenderingType, + context: BasicCrawlingContext, # noqa: ARG001 + use_state: UseStateFunction | None = None, # noqa: ARG001 + ) -> SubCrawlerRun: + if rendering_type == 'client only': + return SubCrawlerRun(result=pw_result) + return SubCrawlerRun(result=static_result) + + monkeypatch.setattr(crawler, '_crawl_one', mock_crawl_one) + + async with crawler.statistics: + await crawler._run_request_handler(crawling_context) + + predictor.store_result.assert_called_once_with(crawling_context.request, 'static') + + +async def test_static_success_differing_from_browser_labels_client_only( + crawling_context: BasicCrawlingContext, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A successful static sub-crawler run with differing results trains the predictor with 'client only'.""" + predictor = Mock(spec=RenderingTypePredictor) + predictor.predict.return_value = RenderingTypePrediction( + rendering_type='client only', detection_probability_recommendation=1.0 + ) + crawler = AdaptivePlaywrightCrawler.with_beautifulsoup_static_parser(rendering_type_predictor=predictor) + + pw_result = RequestHandlerRunResult(key_value_store_getter=AsyncMock()) + await pw_result.push_data({'data': 'from_pw'}) + static_result = RequestHandlerRunResult(key_value_store_getter=AsyncMock()) + await static_result.push_data({'data': 'from_static'}) + + async def mock_crawl_one( + rendering_type: RenderingType, + context: BasicCrawlingContext, # noqa: ARG001 + use_state: UseStateFunction | None = None, # noqa: ARG001 + ) -> SubCrawlerRun: + if rendering_type == 'client only': + return SubCrawlerRun(result=pw_result) + return SubCrawlerRun(result=static_result) + + monkeypatch.setattr(crawler, '_crawl_one', mock_crawl_one) + + async with crawler.statistics: + await crawler._run_request_handler(crawling_context) + + predictor.store_result.assert_called_once_with(crawling_context.request, 'client only') From d6076b5ded581233bc8c42170b2535a0d979ceb6 Mon Sep 17 00:00:00 2001 From: chalakbilla Date: Thu, 12 Nov 2026 03:09:53 +0530 Subject: [PATCH 2/4] refactor(adaptive-crawler): improve transient error classification and test helper --- .../_adaptive_playwright_crawler.py | 12 +++-- .../test_adaptive_playwright_crawler.py | 48 +++++++++---------- 2 files changed, 32 insertions(+), 28 deletions(-) diff --git a/src/crawlee/crawlers/_adaptive_playwright/_adaptive_playwright_crawler.py b/src/crawlee/crawlers/_adaptive_playwright/_adaptive_playwright_crawler.py index feacfe9555..4a7813d957 100644 --- a/src/crawlee/crawlers/_adaptive_playwright/_adaptive_playwright_crawler.py +++ b/src/crawlee/crawlers/_adaptive_playwright/_adaptive_playwright_crawler.py @@ -456,13 +456,17 @@ async def use_initial_state_copy( static_run = await self._crawl_one('static', context=context, use_state=use_initial_state_copy) static_exception = static_run.exception - if isinstance(static_exception, (ContextPipelineInitializationError, RequestHandlerError)): - static_exception = static_exception.wrapped_exception + if isinstance(static_exception, ContextPipelineInitializationError): + is_transient = True + elif isinstance(static_exception, RequestHandlerError): + is_transient = isinstance(static_exception.wrapped_exception, _TRANSIENT_STATIC_ERRORS) + else: + is_transient = isinstance(static_exception, _TRANSIENT_STATIC_ERRORS) - if static_exception is not None and isinstance(static_exception, _TRANSIENT_STATIC_ERRORS): + if static_exception is not None and is_transient: context.log.debug( f'Static run failed with {type(static_exception).__name__}; ' - f'skipping rendering type detection result for {context.request.url}.' + f'discarding rendering type detection for {context.request.url}.' ) detection_result = None elif static_run.result and self.result_comparator(static_run.result, pw_run.result): diff --git a/tests/unit/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py b/tests/unit/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py index 608da44d30..bb1c65eab1 100644 --- a/tests/unit/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py +++ b/tests/unit/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py @@ -23,6 +23,10 @@ from crawlee._types import UseStateFunction +class _HttpClientTransportError(Exception): + """Stands in for transport errors from HTTP client libraries that don't subclass builtin connection errors.""" + + @pytest.fixture def crawling_context() -> BasicCrawlingContext: return BasicCrawlingContext( @@ -39,6 +43,15 @@ def crawling_context() -> BasicCrawlingContext: ) +def _make_crawler_and_predictor() -> tuple[AdaptivePlaywrightCrawler, Mock]: + predictor = Mock(spec=RenderingTypePredictor) + predictor.predict.return_value = RenderingTypePrediction( + rendering_type='client only', detection_probability_recommendation=1.0 + ) + crawler = AdaptivePlaywrightCrawler.with_beautifulsoup_static_parser(rendering_type_predictor=predictor) + return crawler, predictor + + @pytest.mark.parametrize( 'optional_module_name', [ @@ -81,6 +94,13 @@ def test_import_error_handled(optional_module_name: str) -> None: ), id='pipeline-initialization-connection-error', ), + pytest.param( + ContextPipelineInitializationError( + _HttpClientTransportError('Read failed'), + Mock(spec=BasicCrawlingContext), + ), + id='http-client-transport-error', + ), ], ) async def test_transient_failure_skips_rendering_type_detection( @@ -89,12 +109,7 @@ async def test_transient_failure_skips_rendering_type_detection( monkeypatch: pytest.MonkeyPatch, ) -> None: """A transient infrastructure error in the static sub-crawler skips training the predictor.""" - predictor = Mock(spec=RenderingTypePredictor) - predictor.predict.return_value = RenderingTypePrediction( - rendering_type='client only', detection_probability_recommendation=1.0 - ) - crawler = AdaptivePlaywrightCrawler.with_beautifulsoup_static_parser(rendering_type_predictor=predictor) - + crawler, predictor = _make_crawler_and_predictor() pw_result = RequestHandlerRunResult(key_value_store_getter=AsyncMock()) async def mock_crawl_one( @@ -134,12 +149,7 @@ async def test_handler_error_labels_client_only( monkeypatch: pytest.MonkeyPatch, ) -> None: """A handler error in the static sub-crawler trains the predictor with 'client only'.""" - predictor = Mock(spec=RenderingTypePredictor) - predictor.predict.return_value = RenderingTypePrediction( - rendering_type='client only', detection_probability_recommendation=1.0 - ) - crawler = AdaptivePlaywrightCrawler.with_beautifulsoup_static_parser(rendering_type_predictor=predictor) - + crawler, predictor = _make_crawler_and_predictor() pw_result = RequestHandlerRunResult(key_value_store_getter=AsyncMock()) async def mock_crawl_one( @@ -164,12 +174,7 @@ async def test_static_success_matching_browser_labels_static( monkeypatch: pytest.MonkeyPatch, ) -> None: """A successful static sub-crawler run matching the browser run trains the predictor with 'static'.""" - predictor = Mock(spec=RenderingTypePredictor) - predictor.predict.return_value = RenderingTypePrediction( - rendering_type='client only', detection_probability_recommendation=1.0 - ) - crawler = AdaptivePlaywrightCrawler.with_beautifulsoup_static_parser(rendering_type_predictor=predictor) - + crawler, predictor = _make_crawler_and_predictor() pw_result = RequestHandlerRunResult(key_value_store_getter=AsyncMock()) await pw_result.push_data({'data': 'foo'}) static_result = RequestHandlerRunResult(key_value_store_getter=AsyncMock()) @@ -197,12 +202,7 @@ async def test_static_success_differing_from_browser_labels_client_only( monkeypatch: pytest.MonkeyPatch, ) -> None: """A successful static sub-crawler run with differing results trains the predictor with 'client only'.""" - predictor = Mock(spec=RenderingTypePredictor) - predictor.predict.return_value = RenderingTypePrediction( - rendering_type='client only', detection_probability_recommendation=1.0 - ) - crawler = AdaptivePlaywrightCrawler.with_beautifulsoup_static_parser(rendering_type_predictor=predictor) - + crawler, predictor = _make_crawler_and_predictor() pw_result = RequestHandlerRunResult(key_value_store_getter=AsyncMock()) await pw_result.push_data({'data': 'from_pw'}) static_result = RequestHandlerRunResult(key_value_store_getter=AsyncMock()) From 8a580a38d9c57a6906d0531862202e36daf66eb3 Mon Sep 17 00:00:00 2001 From: chalakbilla Date: Thu, 12 Nov 2026 09:00:16 +0530 Subject: [PATCH 3/4] fix(adaptive-crawler): improve inconclusive static error handling and add integration tests --- .../_adaptive_playwright_crawler.py | 62 +++++++++------- .../test_adaptive_playwright_crawler.py | 74 ++++++++++++++++++- .../test_adaptive_playwright_crawler.py | 9 ++- 3 files changed, 116 insertions(+), 29 deletions(-) diff --git a/src/crawlee/crawlers/_adaptive_playwright/_adaptive_playwright_crawler.py b/src/crawlee/crawlers/_adaptive_playwright/_adaptive_playwright_crawler.py index 4a7813d957..abf72eaf67 100644 --- a/src/crawlee/crawlers/_adaptive_playwright/_adaptive_playwright_crawler.py +++ b/src/crawlee/crawlers/_adaptive_playwright/_adaptive_playwright_crawler.py @@ -1,6 +1,5 @@ from __future__ import annotations -import asyncio import logging from collections.abc import Awaitable, Callable, Coroutine from copy import deepcopy @@ -33,10 +32,10 @@ from crawlee.crawlers._playwright._playwright_crawler import _PlaywrightCrawlerAdditionalOptions from crawlee.errors import ( ContextPipelineInitializationError, - ProxyError, RequestHandlerError, RequestThrottledError, SessionError, + UserHandlerTimeoutError, ) from crawlee.statistics import Statistics, StatisticsState @@ -59,16 +58,6 @@ from crawlee.crawlers._basic._basic_crawler import _BasicCrawlerOptions -# Infrastructure errors during static sub-crawler runs that do not indicate whether a page requires -# client-side rendering. -_TRANSIENT_STATIC_ERRORS: tuple[type[BaseException], ...] = ( - SessionError, - ProxyError, - ConnectionError, - TimeoutError, - asyncio.TimeoutError, -) - TStaticParseResult = TypeVar('TStaticParseResult') TStaticSelectResult = TypeVar('TStaticSelectResult') TStaticCrawlingContext = TypeVar('TStaticCrawlingContext', bound=ParsedHttpCrawlingContext) @@ -454,27 +443,20 @@ async def use_initial_state_copy( if should_detect_rendering_type: detection_result: RenderingType | None static_run = await self._crawl_one('static', context=context, use_state=use_initial_state_copy) - - static_exception = static_run.exception - if isinstance(static_exception, ContextPipelineInitializationError): - is_transient = True - elif isinstance(static_exception, RequestHandlerError): - is_transient = isinstance(static_exception.wrapped_exception, _TRANSIENT_STATIC_ERRORS) - else: - is_transient = isinstance(static_exception, _TRANSIENT_STATIC_ERRORS) - - if static_exception is not None and is_transient: - context.log.debug( - f'Static run failed with {type(static_exception).__name__}; ' - f'discarding rendering type detection for {context.request.url}.' - ) + if static_run.exception is not None and _is_inconclusive_static_failure(static_run.exception): detection_result = None elif static_run.result and self.result_comparator(static_run.result, pw_run.result): detection_result = 'static' else: detection_result = 'client only' - if detection_result is not None: + if detection_result is None: + context.log.debug( + f'Static crawler failed during rendering type detection for {context.request.url}, ' + 'the result is not used', + exc_info=static_run.exception, + ) + else: context.log.debug(f'Detected rendering type {detection_result} for {context.request.url}') self.rendering_type_predictor.store_result(context.request, detection_result) @@ -541,6 +523,32 @@ def track_rendering_type_mispredictions(self) -> None: self.statistics.state.rendering_type_mispredictions += 1 +def _is_inconclusive_static_failure(exception: Exception) -> bool: + """Tell whether a failed static run says nothing about whether the page needs a browser. + + Failures that happen before the request handler can process the response are inconclusive: the request could not + be fetched or the response could not be prepared (`ContextPipelineInitializationError`), the session was blocked + (`SessionError`), the request was throttled or it timed out. An exception raised by the request handler itself, + for example because an element is missing in the static content, is evidence that the page needs a browser. + """ + if isinstance(exception, ContextPipelineInitializationError): + return True + + if isinstance(exception, RequestHandlerError): + exception = exception.wrapped_exception + + transient_errors: tuple[type[Exception], ...] = ( + SessionError, + RequestThrottledError, + TimeoutError, + ConnectionError, + ) + if 'UserHandlerTimeoutError' in globals(): + transient_errors += (UserHandlerTimeoutError,) + + return isinstance(exception, transient_errors) + + @dataclass(frozen=True) class SubCrawlerRun: result: RequestHandlerRunResult | None = None diff --git a/tests/integration/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py b/tests/integration/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py index 76a2f40369..4aa01458cd 100644 --- a/tests/integration/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py +++ b/tests/integration/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py @@ -29,7 +29,7 @@ AdaptivePlaywrightCrawlerStatisticState, ) from crawlee.crawlers._adaptive_playwright._adaptive_playwright_crawling_context import AdaptiveContextError -from crawlee.errors import RequestThrottledError +from crawlee.errors import RequestThrottledError, SessionError from crawlee.http_clients import HttpClient, HttpCrawlingResult from crawlee.sessions import SessionPool from crawlee.statistics import Statistics @@ -455,6 +455,78 @@ async def request_handler(context: AdaptivePlaywrightCrawlingContext) -> None: mocked_store_result.assert_called_once_with(mocked_predict.call_args[0][0], expected_result_rendering_type) +async def test_detection_run_failing_to_fetch_is_not_stored(test_urls: list[str]) -> None: + """Test that a static detection run that can't fetch the page does not train the predictor.""" + predictor = _SimpleRenderingTypePredictor() + http_client = AsyncMock(spec=HttpClient) + http_client.crawl.side_effect = ConnectionResetError('Connection reset by peer') + crawler = AdaptivePlaywrightCrawler.with_beautifulsoup_static_parser( + rendering_type_predictor=predictor, + http_client=http_client, + ) + handler_calls = Mock() + + @crawler.router.default_handler + async def request_handler(context: AdaptivePlaywrightCrawlingContext) -> None: + context.page # noqa: B018 Intentionally "useless expression". Raises outside the browser sub crawler. + handler_calls() + + with patch.object(predictor, 'store_result', Mock()) as mocked_store_result: + await crawler.run(test_urls[:1]) + + # Only the browser run reached the handler. The static run failed while fetching the page. + handler_calls.assert_called_once_with() + http_client.crawl.assert_awaited_once() + mocked_store_result.assert_not_called() + + +@pytest.mark.parametrize( + 'static_error', + [ + pytest.param(SessionError('Blocked'), id='Session error'), + pytest.param(asyncio.TimeoutError(), id='Timeout'), + pytest.param(RequestThrottledError(), id='Throttled'), + ], +) +async def test_detection_run_inconclusive_error_in_static_handler_is_not_stored( + static_error: Exception, test_urls: list[str] +) -> None: + """Test that a static detection run that fails with an inconclusive error does not train the predictor.""" + predictor = _SimpleRenderingTypePredictor() + crawler = AdaptivePlaywrightCrawler.with_beautifulsoup_static_parser(rendering_type_predictor=predictor) + + @crawler.router.default_handler + async def request_handler(context: AdaptivePlaywrightCrawlingContext) -> None: + try: + context.page # noqa: B018 Intentionally "useless expression". Raises outside the browser sub crawler. + except AdaptiveContextError: + raise static_error from None + + with patch.object(predictor, 'store_result', Mock()) as mocked_store_result: + await crawler.run(test_urls[:1]) + + mocked_store_result.assert_not_called() + + +async def test_detection_run_error_in_static_handler_is_stored_as_client_only(test_urls: list[str]) -> None: + """Test that a static handler failing on its own, e.g. on a missing element, is still a `client only` signal.""" + predictor = _SimpleRenderingTypePredictor() + crawler = AdaptivePlaywrightCrawler.with_beautifulsoup_static_parser(rendering_type_predictor=predictor) + + @crawler.router.default_handler + async def request_handler(context: AdaptivePlaywrightCrawlingContext) -> None: + try: + context.page # noqa: B018 Intentionally "useless expression". Raises outside the browser sub crawler. + except AdaptiveContextError: + raise ValueError('Element not found in the static content') from None + + with patch.object(predictor, 'store_result', Mock()) as mocked_store_result: + await crawler.run(test_urls[:1]) + + mocked_store_result.assert_called_once() + assert mocked_store_result.call_args.args[1] == 'client only' + + async def test_adaptive_crawling_result_use_state_isolation( key_value_store: KeyValueStore, test_urls: list[str] ) -> None: diff --git a/tests/unit/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py b/tests/unit/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py index bb1c65eab1..9c2ab28aa5 100644 --- a/tests/unit/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py +++ b/tests/unit/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py @@ -17,7 +17,13 @@ RenderingTypePredictor, ) from crawlee.crawlers._adaptive_playwright._adaptive_playwright_crawler import SubCrawlerRun -from crawlee.errors import ContextPipelineInitializationError, ProxyError, RequestHandlerError, SessionError +from crawlee.errors import ( + ContextPipelineInitializationError, + ProxyError, + RequestHandlerError, + RequestThrottledError, + SessionError, +) if TYPE_CHECKING: from crawlee._types import UseStateFunction @@ -87,6 +93,7 @@ def test_import_error_handled(optional_module_name: str) -> None: pytest.param(ConnectionResetError('Connection reset by peer'), id='connection-error'), pytest.param(TimeoutError('Request timed out'), id='timeout-error'), pytest.param(asyncio.TimeoutError('Asyncio timeout'), id='asyncio-timeout-error'), + pytest.param(RequestThrottledError(), id='request-throttled-error'), pytest.param( ContextPipelineInitializationError( ConnectionResetError('Connection reset by peer'), From 7b0fcfef9dc782e9e6fbf77c38b844110ecca121 Mon Sep 17 00:00:00 2001 From: Jan Buchar Date: Fri, 4 Dec 2026 13:57:45 +0100 Subject: [PATCH 4/4] Address review feedback --- .../_adaptive_playwright_crawler.py | 28 +-- .../test_adaptive_playwright_crawler.py | 59 ++--- .../test_adaptive_playwright_crawler.py | 201 +----------------- 3 files changed, 31 insertions(+), 257 deletions(-) diff --git a/src/crawlee/crawlers/_adaptive_playwright/_adaptive_playwright_crawler.py b/src/crawlee/crawlers/_adaptive_playwright/_adaptive_playwright_crawler.py index abf72eaf67..e8833f7617 100644 --- a/src/crawlee/crawlers/_adaptive_playwright/_adaptive_playwright_crawler.py +++ b/src/crawlee/crawlers/_adaptive_playwright/_adaptive_playwright_crawler.py @@ -1,5 +1,6 @@ from __future__ import annotations +import asyncio import logging from collections.abc import Awaitable, Callable, Coroutine from copy import deepcopy @@ -32,10 +33,10 @@ from crawlee.crawlers._playwright._playwright_crawler import _PlaywrightCrawlerAdditionalOptions from crawlee.errors import ( ContextPipelineInitializationError, + HttpStatusCodeError, + ProxyError, RequestHandlerError, RequestThrottledError, - SessionError, - UserHandlerTimeoutError, ) from crawlee.statistics import Statistics, StatisticsState @@ -526,27 +527,14 @@ def track_rendering_type_mispredictions(self) -> None: def _is_inconclusive_static_failure(exception: Exception) -> bool: """Tell whether a failed static run says nothing about whether the page needs a browser. - Failures that happen before the request handler can process the response are inconclusive: the request could not - be fetched or the response could not be prepared (`ContextPipelineInitializationError`), the session was blocked - (`SessionError`), the request was throttled or it timed out. An exception raised by the request handler itself, - for example because an element is missing in the static content, is evidence that the page needs a browser. + A static run that could not fetch or prepare the page (a connection error, a proxy error, throttling) or that timed + out is inconclusive. A blocked session, an error status code, or an exception raised by the request handler is + evidence that the page needs a browser. """ if isinstance(exception, ContextPipelineInitializationError): - return True + return not isinstance(exception.wrapped_exception, HttpStatusCodeError) - if isinstance(exception, RequestHandlerError): - exception = exception.wrapped_exception - - transient_errors: tuple[type[Exception], ...] = ( - SessionError, - RequestThrottledError, - TimeoutError, - ConnectionError, - ) - if 'UserHandlerTimeoutError' in globals(): - transient_errors += (UserHandlerTimeoutError,) - - return isinstance(exception, transient_errors) + return isinstance(exception, (ProxyError, asyncio.TimeoutError)) @dataclass(frozen=True) diff --git a/tests/integration/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py b/tests/integration/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py index 4aa01458cd..ebf640cf3f 100644 --- a/tests/integration/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py +++ b/tests/integration/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py @@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, cast from unittest.mock import AsyncMock, Mock, call, patch +import impit import pytest from bs4 import Tag from parsel import Selector @@ -29,7 +30,7 @@ AdaptivePlaywrightCrawlerStatisticState, ) from crawlee.crawlers._adaptive_playwright._adaptive_playwright_crawling_context import AdaptiveContextError -from crawlee.errors import RequestThrottledError, SessionError +from crawlee.errors import ProxyError, RequestThrottledError from crawlee.http_clients import HttpClient, HttpCrawlingResult from crawlee.sessions import SessionPool from crawlee.statistics import Statistics @@ -455,57 +456,41 @@ async def request_handler(context: AdaptivePlaywrightCrawlingContext) -> None: mocked_store_result.assert_called_once_with(mocked_predict.call_args[0][0], expected_result_rendering_type) -async def test_detection_run_failing_to_fetch_is_not_stored(test_urls: list[str]) -> None: - """Test that a static detection run that can't fetch the page does not train the predictor.""" - predictor = _SimpleRenderingTypePredictor() - http_client = AsyncMock(spec=HttpClient) - http_client.crawl.side_effect = ConnectionResetError('Connection reset by peer') - crawler = AdaptivePlaywrightCrawler.with_beautifulsoup_static_parser( - rendering_type_predictor=predictor, - http_client=http_client, - ) - handler_calls = Mock() - - @crawler.router.default_handler - async def request_handler(context: AdaptivePlaywrightCrawlingContext) -> None: - context.page # noqa: B018 Intentionally "useless expression". Raises outside the browser sub crawler. - handler_calls() - - with patch.object(predictor, 'store_result', Mock()) as mocked_store_result: - await crawler.run(test_urls[:1]) - - # Only the browser run reached the handler. The static run failed while fetching the page. - handler_calls.assert_called_once_with() - http_client.crawl.assert_awaited_once() - mocked_store_result.assert_not_called() +def _http_result(status_code: int) -> HttpCrawlingResult: + return HttpCrawlingResult(http_response=Mock(status_code=status_code, headers={}, read=AsyncMock(return_value=b''))) @pytest.mark.parametrize( - 'static_error', + ('static_fetch_outcome', 'expected_stored'), [ - pytest.param(SessionError('Blocked'), id='Session error'), - pytest.param(asyncio.TimeoutError(), id='Timeout'), - pytest.param(RequestThrottledError(), id='Throttled'), + pytest.param(impit.ConnectError('Connection reset by peer'), [], id='connection-error'), + pytest.param(asyncio.TimeoutError(), [], id='timeout'), + pytest.param(ProxyError(), [], id='proxy-error'), + pytest.param(_http_result(403), ['client only'], id='blocked-status-code'), + pytest.param(_http_result(404), ['client only'], id='client-error-status-code'), ], ) -async def test_detection_run_inconclusive_error_in_static_handler_is_not_stored( - static_error: Exception, test_urls: list[str] +async def test_detection_run_static_fetch_failure( + static_fetch_outcome: Exception | HttpCrawlingResult, expected_stored: list[str], test_urls: list[str] ) -> None: - """Test that a static detection run that fails with an inconclusive error does not train the predictor.""" + """Test that only a static detection run that is blocked or gets an error status code trains the predictor.""" predictor = _SimpleRenderingTypePredictor() - crawler = AdaptivePlaywrightCrawler.with_beautifulsoup_static_parser(rendering_type_predictor=predictor) + http_client = AsyncMock(spec=HttpClient) + http_client.crawl.side_effect = [static_fetch_outcome] + crawler = AdaptivePlaywrightCrawler.with_beautifulsoup_static_parser( + rendering_type_predictor=predictor, + http_client=http_client, + ) @crawler.router.default_handler async def request_handler(context: AdaptivePlaywrightCrawlingContext) -> None: - try: - context.page # noqa: B018 Intentionally "useless expression". Raises outside the browser sub crawler. - except AdaptiveContextError: - raise static_error from None + await context.push_data({'url': context.request.url}) with patch.object(predictor, 'store_result', Mock()) as mocked_store_result: await crawler.run(test_urls[:1]) - mocked_store_result.assert_not_called() + http_client.crawl.assert_awaited_once() + assert [c.args[1] for c in mocked_store_result.call_args_list] == expected_stored async def test_detection_run_error_in_static_handler_is_stored_as_client_only(test_urls: list[str]) -> None: diff --git a/tests/unit/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py b/tests/unit/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py index 9c2ab28aa5..04141c49c1 100644 --- a/tests/unit/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py +++ b/tests/unit/crawlers/_adaptive_playwright/test_adaptive_playwright_crawler.py @@ -1,62 +1,10 @@ from __future__ import annotations -import asyncio -import logging import sys -from typing import TYPE_CHECKING -from unittest.mock import AsyncMock, Mock, patch +from unittest.mock import patch import pytest -from crawlee._request import Request -from crawlee._types import BasicCrawlingContext, RequestHandlerRunResult -from crawlee.crawlers import ( - AdaptivePlaywrightCrawler, - RenderingType, - RenderingTypePrediction, - RenderingTypePredictor, -) -from crawlee.crawlers._adaptive_playwright._adaptive_playwright_crawler import SubCrawlerRun -from crawlee.errors import ( - ContextPipelineInitializationError, - ProxyError, - RequestHandlerError, - RequestThrottledError, - SessionError, -) - -if TYPE_CHECKING: - from crawlee._types import UseStateFunction - - -class _HttpClientTransportError(Exception): - """Stands in for transport errors from HTTP client libraries that don't subclass builtin connection errors.""" - - -@pytest.fixture -def crawling_context() -> BasicCrawlingContext: - return BasicCrawlingContext( - request=Request.from_url(url='https://example.com/test'), - session=Mock(), - proxy_info=Mock(), - send_request=AsyncMock(), - add_requests=AsyncMock(), - push_data=AsyncMock(), - get_key_value_store=AsyncMock(), - use_state=AsyncMock(return_value={}), - log=logging.getLogger('test'), - register_deferred_cleanup=lambda _: None, - ) - - -def _make_crawler_and_predictor() -> tuple[AdaptivePlaywrightCrawler, Mock]: - predictor = Mock(spec=RenderingTypePredictor) - predictor.predict.return_value = RenderingTypePrediction( - rendering_type='client only', detection_probability_recommendation=1.0 - ) - crawler = AdaptivePlaywrightCrawler.with_beautifulsoup_static_parser(rendering_type_predictor=predictor) - return crawler, predictor - @pytest.mark.parametrize( 'optional_module_name', @@ -83,150 +31,3 @@ def test_import_error_handled(optional_module_name: str) -> None: with pytest.raises(ImportError): from crawlee.crawlers import AdaptivePlaywrightCrawler # noqa: F401 PLC0415 - - -@pytest.mark.parametrize( - 'transient_exception', - [ - pytest.param(SessionError('Session blocked'), id='session-error'), - pytest.param(ProxyError('Proxy connection failed'), id='proxy-error'), - pytest.param(ConnectionResetError('Connection reset by peer'), id='connection-error'), - pytest.param(TimeoutError('Request timed out'), id='timeout-error'), - pytest.param(asyncio.TimeoutError('Asyncio timeout'), id='asyncio-timeout-error'), - pytest.param(RequestThrottledError(), id='request-throttled-error'), - pytest.param( - ContextPipelineInitializationError( - ConnectionResetError('Connection reset by peer'), - Mock(spec=BasicCrawlingContext), - ), - id='pipeline-initialization-connection-error', - ), - pytest.param( - ContextPipelineInitializationError( - _HttpClientTransportError('Read failed'), - Mock(spec=BasicCrawlingContext), - ), - id='http-client-transport-error', - ), - ], -) -async def test_transient_failure_skips_rendering_type_detection( - transient_exception: Exception, - crawling_context: BasicCrawlingContext, - monkeypatch: pytest.MonkeyPatch, -) -> None: - """A transient infrastructure error in the static sub-crawler skips training the predictor.""" - crawler, predictor = _make_crawler_and_predictor() - pw_result = RequestHandlerRunResult(key_value_store_getter=AsyncMock()) - - async def mock_crawl_one( - rendering_type: RenderingType, - context: BasicCrawlingContext, # noqa: ARG001 - use_state: UseStateFunction | None = None, # noqa: ARG001 - ) -> SubCrawlerRun: - if rendering_type == 'client only': - return SubCrawlerRun(result=pw_result) - return SubCrawlerRun(exception=transient_exception) - - monkeypatch.setattr(crawler, '_crawl_one', mock_crawl_one) - - async with crawler.statistics: - await crawler._run_request_handler(crawling_context) - - predictor.store_result.assert_not_called() - - -@pytest.mark.parametrize( - 'handler_exception', - [ - pytest.param(AttributeError("'NoneType' object has no attribute 'text'"), id='attribute-error'), - pytest.param(KeyError('price'), id='key-error'), - pytest.param( - RequestHandlerError( - AttributeError("'NoneType' object has no attribute 'text'"), - Mock(spec=BasicCrawlingContext), - ), - id='request-handler-error', - ), - ], -) -async def test_handler_error_labels_client_only( - handler_exception: Exception, - crawling_context: BasicCrawlingContext, - monkeypatch: pytest.MonkeyPatch, -) -> None: - """A handler error in the static sub-crawler trains the predictor with 'client only'.""" - crawler, predictor = _make_crawler_and_predictor() - pw_result = RequestHandlerRunResult(key_value_store_getter=AsyncMock()) - - async def mock_crawl_one( - rendering_type: RenderingType, - context: BasicCrawlingContext, # noqa: ARG001 - use_state: UseStateFunction | None = None, # noqa: ARG001 - ) -> SubCrawlerRun: - if rendering_type == 'client only': - return SubCrawlerRun(result=pw_result) - return SubCrawlerRun(exception=handler_exception) - - monkeypatch.setattr(crawler, '_crawl_one', mock_crawl_one) - - async with crawler.statistics: - await crawler._run_request_handler(crawling_context) - - predictor.store_result.assert_called_once_with(crawling_context.request, 'client only') - - -async def test_static_success_matching_browser_labels_static( - crawling_context: BasicCrawlingContext, - monkeypatch: pytest.MonkeyPatch, -) -> None: - """A successful static sub-crawler run matching the browser run trains the predictor with 'static'.""" - crawler, predictor = _make_crawler_and_predictor() - pw_result = RequestHandlerRunResult(key_value_store_getter=AsyncMock()) - await pw_result.push_data({'data': 'foo'}) - static_result = RequestHandlerRunResult(key_value_store_getter=AsyncMock()) - await static_result.push_data({'data': 'foo'}) - - async def mock_crawl_one( - rendering_type: RenderingType, - context: BasicCrawlingContext, # noqa: ARG001 - use_state: UseStateFunction | None = None, # noqa: ARG001 - ) -> SubCrawlerRun: - if rendering_type == 'client only': - return SubCrawlerRun(result=pw_result) - return SubCrawlerRun(result=static_result) - - monkeypatch.setattr(crawler, '_crawl_one', mock_crawl_one) - - async with crawler.statistics: - await crawler._run_request_handler(crawling_context) - - predictor.store_result.assert_called_once_with(crawling_context.request, 'static') - - -async def test_static_success_differing_from_browser_labels_client_only( - crawling_context: BasicCrawlingContext, - monkeypatch: pytest.MonkeyPatch, -) -> None: - """A successful static sub-crawler run with differing results trains the predictor with 'client only'.""" - crawler, predictor = _make_crawler_and_predictor() - pw_result = RequestHandlerRunResult(key_value_store_getter=AsyncMock()) - await pw_result.push_data({'data': 'from_pw'}) - static_result = RequestHandlerRunResult(key_value_store_getter=AsyncMock()) - await static_result.push_data({'data': 'from_static'}) - - async def mock_crawl_one( - rendering_type: RenderingType, - context: BasicCrawlingContext, # noqa: ARG001 - use_state: UseStateFunction | None = None, # noqa: ARG001 - ) -> SubCrawlerRun: - if rendering_type == 'client only': - return SubCrawlerRun(result=pw_result) - return SubCrawlerRun(result=static_result) - - monkeypatch.setattr(crawler, '_crawl_one', mock_crawl_one) - - async with crawler.statistics: - await crawler._run_request_handler(crawling_context) - - predictor.store_result.assert_called_once_with(crawling_context.request, 'client only')