Repository navigation
fix(adaptive-crawler): Skip transient static failures in rendering type detection #2438
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
da3e5b1
d6076b5
8a580a3
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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, | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Important: In the static pipeline, ✍️ Drafted by Claude Code |
||
| RequestThrottledError, | ||
| TimeoutError, | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Important: On Python 3.10, ✍️ Drafted by Claude Code |
||
| ConnectionError, | ||
| ) | ||
| if 'UserHandlerTimeoutError' in globals(): | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Suggestion: ✍️ Drafted by Claude Code |
||
| transient_errors += (UserHandlerTimeoutError,) | ||
|
|
||
| return isinstance(exception, transient_errors) | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class SubCrawlerRun: | ||
| result: RequestHandlerRunResult | None = None | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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( | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit: The four unit tests repeat this ✍️ Drafted by Claude Code |
||
| 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') | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Question: The docstring says that an exception raised by the request handler itself is evidence that the page needs a browser. After this unwrap, a
UserHandlerTimeoutError,ConnectionErrororRequestThrottledErrorraised in the handler counts as inconclusive. Which behavior is intended? The docstring and the code should match.✍️ Drafted by Claude Code