diff --git a/src/crawlee/crawlers/_adaptive_playwright/_adaptive_playwright_crawler.py b/src/crawlee/crawlers/_adaptive_playwright/_adaptive_playwright_crawler.py index 9f498f0b13..abf72eaf67 100644 --- a/src/crawlee/crawlers/_adaptive_playwright/_adaptive_playwright_crawler.py +++ b/src/crawlee/crawlers/_adaptive_playwright/_adaptive_playwright_crawler.py @@ -30,7 +30,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, + RequestHandlerError, + RequestThrottledError, + SessionError, + UserHandlerTimeoutError, +) from crawlee.statistics import Statistics, StatisticsState from ._adaptive_playwright_crawler_statistics import AdaptivePlaywrightCrawlerStatisticState @@ -435,15 +441,24 @@ 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): + 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' - 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 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) self._context_result_map[context] = pw_run.result @@ -508,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 04141c49c1..9c2ab28aa5 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,62 @@ 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, + 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', @@ -31,3 +83,150 @@ 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')