Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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

Copy link
Copy Markdown
Collaborator

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, ConnectionError or RequestThrottledError raised in the handler counts as inconclusive. Which behavior is intended? The docstring and the code should match.

✍️ Drafted by Claude Code


transient_errors: tuple[type[Exception], ...] = (
SessionError,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: In the static pipeline, SessionError means the site blocked the HTTP client (a blocked status code or a block detected in the content). Line 534 also skips every ContextPipelineInitializationError, including a 403 wrapped as HttpClientStatusCodeError. When the browser run then succeeds, that is a repeatable signal for client only, not a transient failure. With no stored results, DefaultRenderingTypePredictor.predict() keeps returning detection_probability_recommendation=1, so on a site that blocks plain HTTP every request runs both crawls. A local repro with 6 URLs, a static run that always gets 403, and a browser run that succeeds: this PR stores 0 results and detection stays at 1; master stores 4 and detection drops to 0.1. Could you treat only fetch failures as inconclusive (connection errors, timeouts, ProxyError, RequestThrottledError) and keep blocks and status code errors as client only?

✍️ Drafted by Claude Code

RequestThrottledError,
TimeoutError,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: On Python 3.10, asyncio.TimeoutError is not a subclass of TimeoutError. The handler timeout raised by wait_for in _crawl_one is still stored as client only there, and test_transient_failure_skips_rendering_type_detection[asyncio-timeout-error] fails on 3.10 (checked locally; 3.10 is in the CI matrix). Please add asyncio.TimeoutError to the tuple.

✍️ Drafted by Claude Code

ConnectionError,
)
if 'UserHandlerTimeoutError' in globals():

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: 'UserHandlerTimeoutError' in globals() is always true, because the class is imported at the top of the module. Please drop the check and define the tuple once as a module-level constant that includes UserHandlerTimeoutError.

✍️ Drafted by Claude Code

transient_errors += (UserHandlerTimeoutError,)

return isinstance(exception, transient_errors)


@dataclass(frozen=True)
class SubCrawlerRun:
result: RequestHandlerRunResult | None = None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
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',
Expand All @@ -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(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: The four unit tests repeat this mock_crawl_one stub, and the new integration tests already cover the same cases. Could you merge them into one parametrized test that patches _crawl_one with AsyncMock(side_effect=...), or drop them?

✍️ 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')
Loading