|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import logging |
| 4 | +from abc import ABC |
| 5 | +from typing import TYPE_CHECKING, Any, Generic |
| 6 | + |
| 7 | +from pydantic import ValidationError |
| 8 | +from typing_extensions import NotRequired, TypeVar |
| 9 | + |
| 10 | +from crawlee import EnqueueStrategy |
| 11 | +from crawlee._request import BaseRequestData |
| 12 | +from crawlee._utils.docs import docs_group |
| 13 | +from crawlee._utils.urls import convert_to_absolute_url, is_url_absolute |
| 14 | +from crawlee.abstract_http_crawler._http_crawling_context import ( |
| 15 | + HttpCrawlingContext, |
| 16 | + ParsedHttpCrawlingContext, |
| 17 | + TParseResult, |
| 18 | +) |
| 19 | +from crawlee.basic_crawler import BasicCrawler, BasicCrawlerOptions, ContextPipeline |
| 20 | +from crawlee.errors import SessionError |
| 21 | +from crawlee.http_clients import HttpxHttpClient |
| 22 | + |
| 23 | +if TYPE_CHECKING: |
| 24 | + from collections.abc import AsyncGenerator, Iterable |
| 25 | + |
| 26 | + from typing_extensions import Unpack |
| 27 | + |
| 28 | + from crawlee._types import BasicCrawlingContext, EnqueueLinksFunction, EnqueueLinksKwargs |
| 29 | + from crawlee.abstract_http_crawler._abstract_http_parser import AbstractHttpParser |
| 30 | + |
| 31 | +TCrawlingContext = TypeVar('TCrawlingContext', bound=ParsedHttpCrawlingContext) |
| 32 | + |
| 33 | + |
| 34 | +@docs_group('Data structures') |
| 35 | +class HttpCrawlerOptions(Generic[TCrawlingContext], BasicCrawlerOptions[TCrawlingContext]): |
| 36 | + """Arguments for the `AbstractHttpCrawler` constructor. |
| 37 | +
|
| 38 | + It is intended for typing forwarded `__init__` arguments in the subclasses. |
| 39 | + """ |
| 40 | + |
| 41 | + additional_http_error_status_codes: NotRequired[Iterable[int]] |
| 42 | + """Additional HTTP status codes to treat as errors, triggering automatic retries when encountered.""" |
| 43 | + |
| 44 | + ignore_http_error_status_codes: NotRequired[Iterable[int]] |
| 45 | + """HTTP status codes typically considered errors but to be treated as successful responses.""" |
| 46 | + |
| 47 | + |
| 48 | +@docs_group('Abstract classes') |
| 49 | +class AbstractHttpCrawler(Generic[TCrawlingContext, TParseResult], BasicCrawler[TCrawlingContext], ABC): |
| 50 | + """A web crawler for performing HTTP requests. |
| 51 | +
|
| 52 | + The `AbstractHttpCrawler` builds on top of the `BasicCrawler`, which means it inherits all of its features. On top |
| 53 | + of that it implements the HTTP communication using the HTTP clients. The class allows integration with |
| 54 | + any HTTP client that implements the `BaseHttpClient` interface. The HTTP client is provided to the crawler |
| 55 | + as an input parameter to the constructor. |
| 56 | + AbstractHttpCrawler is generic class and is expected to be used together with specific parser that will be used to |
| 57 | + parse http response and type of expected TCrawlingContext which is available to the user function. |
| 58 | + See prepared specific version of it: BeautifulSoupCrawler, ParselCrawler or HttpCrawler for example. |
| 59 | +
|
| 60 | + The HTTP client-based crawlers are ideal for websites that do not require JavaScript execution. However, |
| 61 | + if you need to execute client-side JavaScript, consider using a browser-based crawler like the `PlaywrightCrawler`. |
| 62 | + """ |
| 63 | + |
| 64 | + def __init__( |
| 65 | + self, |
| 66 | + *, |
| 67 | + parser: AbstractHttpParser[TParseResult], |
| 68 | + additional_http_error_status_codes: Iterable[int] = (), |
| 69 | + ignore_http_error_status_codes: Iterable[int] = (), |
| 70 | + **kwargs: Unpack[BasicCrawlerOptions[TCrawlingContext]], |
| 71 | + ) -> None: |
| 72 | + self._parser = parser |
| 73 | + |
| 74 | + kwargs.setdefault( |
| 75 | + 'http_client', |
| 76 | + HttpxHttpClient( |
| 77 | + additional_http_error_status_codes=additional_http_error_status_codes, |
| 78 | + ignore_http_error_status_codes=ignore_http_error_status_codes, |
| 79 | + ), |
| 80 | + ) |
| 81 | + |
| 82 | + if '_context_pipeline' not in kwargs: |
| 83 | + raise ValueError( |
| 84 | + 'Please pass in a `_context_pipeline`. You should use the ' |
| 85 | + 'AbstractHttpCrawler._create_static_content_crawler_pipeline() method to initialize it.' |
| 86 | + ) |
| 87 | + |
| 88 | + kwargs.setdefault('_logger', logging.getLogger(__name__)) |
| 89 | + super().__init__(**kwargs) |
| 90 | + |
| 91 | + def _create_static_content_crawler_pipeline(self) -> ContextPipeline[ParsedHttpCrawlingContext[TParseResult]]: |
| 92 | + """Create static content crawler context pipeline with expected pipeline steps.""" |
| 93 | + return ( |
| 94 | + ContextPipeline() |
| 95 | + .compose(self._make_http_request) |
| 96 | + .compose(self._parse_http_response) |
| 97 | + .compose(self._handle_blocked_request) |
| 98 | + ) |
| 99 | + |
| 100 | + async def _parse_http_response( |
| 101 | + self, context: HttpCrawlingContext |
| 102 | + ) -> AsyncGenerator[ParsedHttpCrawlingContext[TParseResult], None]: |
| 103 | + """Parse HTTP response and create context enhanced by the parsing result and enqueue links function. |
| 104 | +
|
| 105 | + Args: |
| 106 | + context: The current crawling context, that includes HTTP response. |
| 107 | +
|
| 108 | + Yields: |
| 109 | + The original crawling context enhanced by the parsing result and enqueue links function. |
| 110 | + """ |
| 111 | + parsed_content = await self._parser.parse(context.http_response) |
| 112 | + yield ParsedHttpCrawlingContext.from_http_crawling_context( |
| 113 | + context=context, |
| 114 | + parsed_content=parsed_content, |
| 115 | + enqueue_links=self._create_enqueue_links_function(context, parsed_content), |
| 116 | + ) |
| 117 | + |
| 118 | + def _create_enqueue_links_function( |
| 119 | + self, context: HttpCrawlingContext, parsed_content: TParseResult |
| 120 | + ) -> EnqueueLinksFunction: |
| 121 | + """Create a callback function for extracting links from parsed content and enqueuing them to the crawl. |
| 122 | +
|
| 123 | + Args: |
| 124 | + context: The current crawling context. |
| 125 | + parsed_content: The parsed http response. |
| 126 | +
|
| 127 | + Returns: |
| 128 | + Awaitable that is used for extracting links from parsed content and enqueuing them to the crawl. |
| 129 | + """ |
| 130 | + |
| 131 | + async def enqueue_links( |
| 132 | + *, |
| 133 | + selector: str = 'a', |
| 134 | + label: str | None = None, |
| 135 | + user_data: dict[str, Any] | None = None, |
| 136 | + **kwargs: Unpack[EnqueueLinksKwargs], |
| 137 | + ) -> None: |
| 138 | + kwargs.setdefault('strategy', EnqueueStrategy.SAME_HOSTNAME) |
| 139 | + |
| 140 | + requests = list[BaseRequestData]() |
| 141 | + user_data = user_data or {} |
| 142 | + if label is not None: |
| 143 | + user_data.setdefault('label', label) |
| 144 | + for link in self._parser.find_links(parsed_content, selector=selector): |
| 145 | + url = link |
| 146 | + if not is_url_absolute(url): |
| 147 | + url = convert_to_absolute_url(context.request.url, url) |
| 148 | + try: |
| 149 | + request = BaseRequestData.from_url(url, user_data=user_data) |
| 150 | + except ValidationError as exc: |
| 151 | + context.log.debug( |
| 152 | + f'Skipping URL "{url}" due to invalid format: {exc}. ' |
| 153 | + 'This may be caused by a malformed URL or unsupported URL scheme. ' |
| 154 | + 'Please ensure the URL is correct and retry.' |
| 155 | + ) |
| 156 | + continue |
| 157 | + |
| 158 | + requests.append(request) |
| 159 | + |
| 160 | + await context.add_requests(requests, **kwargs) |
| 161 | + |
| 162 | + return enqueue_links |
| 163 | + |
| 164 | + async def _make_http_request(self, context: BasicCrawlingContext) -> AsyncGenerator[HttpCrawlingContext, None]: |
| 165 | + """Make http request and create context enhanced by HTTP response. |
| 166 | +
|
| 167 | + Args: |
| 168 | + context: The current crawling context. |
| 169 | +
|
| 170 | + Yields: |
| 171 | + The original crawling context enhanced by HTTP response. |
| 172 | + """ |
| 173 | + result = await self._http_client.crawl( |
| 174 | + request=context.request, |
| 175 | + session=context.session, |
| 176 | + proxy_info=context.proxy_info, |
| 177 | + statistics=self._statistics, |
| 178 | + ) |
| 179 | + |
| 180 | + yield HttpCrawlingContext.from_basic_crawling_context(context=context, http_response=result.http_response) |
| 181 | + |
| 182 | + async def _handle_blocked_request( |
| 183 | + self, context: ParsedHttpCrawlingContext[TParseResult] |
| 184 | + ) -> AsyncGenerator[ParsedHttpCrawlingContext[TParseResult], None]: |
| 185 | + """Try to detect if the request is blocked based on the HTTP status code or the parsed response content. |
| 186 | +
|
| 187 | + Args: |
| 188 | + context: The current crawling context. |
| 189 | +
|
| 190 | + Raises: |
| 191 | + SessionError: If the request is considered blocked. |
| 192 | +
|
| 193 | + Yields: |
| 194 | + The original crawling context if no errors are detected. |
| 195 | + """ |
| 196 | + if self._retry_on_blocked: |
| 197 | + status_code = context.http_response.status_code |
| 198 | + |
| 199 | + # TODO: refactor to avoid private member access |
| 200 | + # https://github.com/apify/crawlee-python/issues/708 |
| 201 | + if ( |
| 202 | + context.session |
| 203 | + and status_code not in self._http_client._ignore_http_error_status_codes # noqa: SLF001 |
| 204 | + and context.session.is_blocked_status_code(status_code=status_code) |
| 205 | + ): |
| 206 | + raise SessionError(f'Assuming the session is blocked based on HTTP status code {status_code}') |
| 207 | + if blocked_info := self._parser.is_blocked(context.parsed_content): |
| 208 | + raise SessionError(blocked_info.reason) |
| 209 | + yield context |
0 commit comments