diff --git a/src/crawlee/crawlers/_adaptive_playwright/_adaptive_playwright_crawler.py b/src/crawlee/crawlers/_adaptive_playwright/_adaptive_playwright_crawler.py index d7cdfeeff9..a0f39ce039 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 contextvars import ContextVar @@ -33,6 +34,8 @@ from crawlee.crawlers._playwright._playwright_crawler import _PlaywrightCrawlerAdditionalOptions from crawlee.errors import ( ContextPipelineInitializationError, + HttpStatusCodeError, + ProxyError, RequestHandlerError, RequestThrottledError, UserDefinedErrorHandlerError, @@ -472,15 +475,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 await self._report_skipped_requests(context, pw_run.skipped_requests) @@ -546,6 +558,19 @@ 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. + + 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 not isinstance(exception.wrapped_exception, HttpStatusCodeError) + + return isinstance(exception, (ProxyError, asyncio.TimeoutError)) + + @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 dc3e2f1fb7..ca67d3dfe7 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 @@ -30,7 +31,7 @@ AdaptivePlaywrightCrawlerStatisticState, ) from crawlee.crawlers._adaptive_playwright._adaptive_playwright_crawling_context import AdaptiveContextError -from crawlee.errors import RequestThrottledError +from crawlee.errors import ProxyError, RequestThrottledError from crawlee.http_clients import HttpClient, HttpCrawlingResult from crawlee.sessions import SessionPool from crawlee.statistics import Statistics @@ -458,6 +459,62 @@ async def request_handler(context: AdaptivePlaywrightCrawlingContext) -> None: mocked_store_result.assert_called_once_with(mocked_predict.call_args[0][0], expected_result_rendering_type) +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_fetch_outcome', 'expected_stored'), + [ + 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_static_fetch_failure( + static_fetch_outcome: Exception | HttpCrawlingResult, expected_stored: list[str], test_urls: list[str] +) -> None: + """Test that only a static detection run that is blocked or gets an error status code trains the predictor.""" + predictor = _SimpleRenderingTypePredictor() + 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: + 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]) + + 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: + """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: