-
Notifications
You must be signed in to change notification settings - Fork 705
Expand file tree
/
Copy path_basic_crawler.py
More file actions
1690 lines (1405 loc) · 73.2 KB
/
_basic_crawler.py
File metadata and controls
1690 lines (1405 loc) · 73.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Inspiration: https://github.com/apify/crawlee/blob/v3.7.3/packages/basic-crawler/src/internals/basic-crawler.ts
from __future__ import annotations
import asyncio
import functools
import logging
import signal
import sys
import tempfile
import threading
import traceback
from asyncio import CancelledError
from collections.abc import AsyncGenerator, Awaitable, Callable, Iterable, Sequence
from contextlib import AsyncExitStack, suppress
from datetime import timedelta
from functools import partial
from io import StringIO
from pathlib import Path
from typing import TYPE_CHECKING, Any, Generic, Literal, ParamSpec, cast
from urllib.parse import ParseResult, urlparse
from weakref import WeakKeyDictionary
from cachetools import LRUCache
from tldextract import TLDExtract
from typing_extensions import NotRequired, TypedDict, TypeVar, Unpack, assert_never
from yarl import URL
from crawlee import EnqueueStrategy, Glob, RequestTransformAction, service_locator
from crawlee._autoscaling import AutoscaledPool, Snapshotter, SystemStatus
from crawlee._log_config import configure_logger, get_configured_log_level, string_to_log_level
from crawlee._request import Request, RequestOptions, RequestState
from crawlee._service_locator import ServiceLocator
from crawlee._types import (
BasicCrawlingContext,
EnqueueLinksKwargs,
ExportDataCsvKwargs,
ExportDataJsonKwargs,
GetKeyValueStoreFromRequestHandlerFunction,
HttpHeaders,
HttpPayload,
LogLevel,
RequestHandlerRunResult,
SendRequestFunction,
SkippedReason,
)
from crawlee._utils.docs import docs_group
from crawlee._utils.file import atomic_write, export_csv_to_stream, export_json_to_stream
from crawlee._utils.recurring_task import RecurringTask
from crawlee._utils.robots import RobotsTxtFile
from crawlee._utils.urls import convert_to_absolute_url, is_url_absolute
from crawlee._utils.wait import wait_for
from crawlee._utils.web import is_status_code_client_error, is_status_code_server_error
from crawlee.errors import (
ContextPipelineInitializationError,
ContextPipelineInterruptedError,
HttpClientStatusCodeError,
HttpStatusCodeError,
RequestCollisionError,
RequestHandlerError,
SessionError,
UserDefinedErrorHandlerError,
UserHandlerTimeoutError,
)
from crawlee.events._types import Event, EventCrawlerStatusData
from crawlee.http_clients import ImpitHttpClient
from crawlee.router import Router
from crawlee.sessions import SessionPool
from crawlee.statistics import Statistics, StatisticsState
from crawlee.storages import Dataset, KeyValueStore, RequestQueue
from ._context_pipeline import ContextPipeline
from ._context_utils import swapped_context
from ._logging_utils import (
get_one_line_error_summary_if_possible,
reduce_asyncio_timeout_error_to_relevant_traceback_parts,
)
if TYPE_CHECKING:
import re
from collections.abc import Iterator
from contextlib import AbstractAsyncContextManager
from crawlee._types import (
ConcurrencySettings,
EnqueueLinksFunction,
ExtractLinksFunction,
GetDataKwargs,
HttpMethod,
JsonSerializable,
PushDataKwargs,
)
from crawlee.configuration import Configuration
from crawlee.events import EventManager
from crawlee.http_clients import HttpClient, HttpResponse
from crawlee.proxy_configuration import ProxyConfiguration, ProxyInfo
from crawlee.request_loaders import RequestManager
from crawlee.sessions import Session
from crawlee.statistics import FinalStatistics
from crawlee.storage_clients import StorageClient
from crawlee.storage_clients.models import DatasetItemsListPage
TCrawlingContext = TypeVar('TCrawlingContext', bound=BasicCrawlingContext, default=BasicCrawlingContext)
TStatisticsState = TypeVar('TStatisticsState', bound=StatisticsState, default=StatisticsState)
TRequestIterator = TypeVar('TRequestIterator', str, Request)
TParams = ParamSpec('TParams')
T = TypeVar('T')
ErrorHandler = Callable[[TCrawlingContext, Exception], Awaitable[Request | None]]
FailedRequestHandler = Callable[[TCrawlingContext, Exception], Awaitable[None]]
SkippedRequestCallback = Callable[[str, SkippedReason], Awaitable[None]]
class _BasicCrawlerOptions(TypedDict):
"""Non-generic options the `BasicCrawler` constructor."""
configuration: NotRequired[Configuration]
"""The `Configuration` instance. Some of its properties are used as defaults for the crawler."""
event_manager: NotRequired[EventManager]
"""The event manager for managing events for the crawler and all its components."""
storage_client: NotRequired[StorageClient]
"""The storage client for managing storages for the crawler and all its components."""
request_manager: NotRequired[RequestManager]
"""Manager of requests that should be processed by the crawler."""
session_pool: NotRequired[SessionPool]
"""A custom `SessionPool` instance, allowing the use of non-default configuration."""
proxy_configuration: NotRequired[ProxyConfiguration]
"""HTTP proxy configuration used when making requests."""
http_client: NotRequired[HttpClient]
"""HTTP client used by `BasicCrawlingContext.send_request` method."""
max_request_retries: NotRequired[int]
"""Specifies the maximum number of retries allowed for a request if its processing fails.
This includes retries due to navigation errors or errors thrown from user-supplied functions
(`request_handler`, `pre_navigation_hooks` etc.).
This limit does not apply to retries triggered by session rotation (see `max_session_rotations`)."""
max_requests_per_crawl: NotRequired[int | None]
"""Maximum number of pages to open during a crawl. The crawl stops upon reaching this limit.
Setting this value can help avoid infinite loops in misconfigured crawlers. `None` means no limit.
Due to concurrency settings, the actual number of pages visited may slightly exceed this value."""
max_session_rotations: NotRequired[int]
"""Maximum number of session rotations per request. The crawler rotates the session if a proxy error occurs
or if the website blocks the request.
The session rotations are not counted towards the `max_request_retries` limit.
"""
max_crawl_depth: NotRequired[int | None]
"""Specifies the maximum crawl depth. If set, the crawler will stop processing links beyond this depth.
The crawl depth starts at 0 for initial requests and increases with each subsequent level of links.
Requests at the maximum depth will still be processed, but no new links will be enqueued from those requests.
If not set, crawling continues without depth restrictions.
"""
use_session_pool: NotRequired[bool]
"""Enable the use of a session pool for managing sessions during crawling."""
retry_on_blocked: NotRequired[bool]
"""If True, the crawler attempts to bypass bot protections automatically."""
concurrency_settings: NotRequired[ConcurrencySettings]
"""Settings to fine-tune concurrency levels."""
request_handler_timeout: NotRequired[timedelta]
"""Maximum duration allowed for a single request handler to run."""
abort_on_error: NotRequired[bool]
"""If True, the crawler stops immediately when any request handler error occurs."""
configure_logging: NotRequired[bool]
"""If True, the crawler will set up logging infrastructure automatically."""
statistics_log_format: NotRequired[Literal['table', 'inline']]
"""If 'table', displays crawler statistics as formatted tables in logs. If 'inline', outputs statistics as plain
text log messages.
"""
keep_alive: NotRequired[bool]
"""Flag that can keep crawler running even when there are no requests in queue."""
additional_http_error_status_codes: NotRequired[Iterable[int]]
"""Additional HTTP status codes to treat as errors, triggering automatic retries when encountered."""
ignore_http_error_status_codes: NotRequired[Iterable[int]]
"""HTTP status codes that are typically considered errors but should be treated as successful responses."""
_additional_context_managers: NotRequired[Sequence[AbstractAsyncContextManager]]
"""Additional context managers used throughout the crawler lifecycle. Intended for use by
subclasses rather than direct instantiation of `BasicCrawler`."""
_logger: NotRequired[logging.Logger]
"""A logger instance, typically provided by a subclass, for consistent logging labels. Intended for use by
subclasses rather than direct instantiation of `BasicCrawler`."""
respect_robots_txt_file: NotRequired[bool]
"""If set to `True`, the crawler will automatically try to fetch the robots.txt file for each domain,
and skip those that are not allowed. This also prevents disallowed URLs to be added via `EnqueueLinksFunction`."""
status_message_logging_interval: NotRequired[timedelta]
"""Interval for logging the crawler status messages."""
status_message_callback: NotRequired[
Callable[[StatisticsState, StatisticsState | None, str], Awaitable[str | None]]
]
"""Allows overriding the default status message. The default status message is provided in the parameters.
Returning `None` suppresses the status message."""
id: NotRequired[int]
"""Identifier used for crawler state tracking. Use the same id across multiple crawlers to share state between
them."""
class _BasicCrawlerOptionsGeneric(TypedDict, Generic[TCrawlingContext, TStatisticsState]):
"""Generic options the `BasicCrawler` constructor."""
request_handler: NotRequired[Callable[[TCrawlingContext], Awaitable[None]]]
"""A callable responsible for handling requests."""
_context_pipeline: NotRequired[ContextPipeline[TCrawlingContext]]
"""Enables extending the request lifecycle and modifying the crawling context. Intended for use by
subclasses rather than direct instantiation of `BasicCrawler`."""
statistics: NotRequired[Statistics[TStatisticsState]]
"""A custom `Statistics` instance, allowing the use of non-default configuration."""
class BasicCrawlerOptions(
_BasicCrawlerOptions,
_BasicCrawlerOptionsGeneric[TCrawlingContext, TStatisticsState],
Generic[TCrawlingContext, TStatisticsState],
):
"""Arguments for the `BasicCrawler` constructor.
It is intended for typing forwarded `__init__` arguments in the subclasses.
"""
@docs_group('Crawlers')
class BasicCrawler(Generic[TCrawlingContext, TStatisticsState]):
"""A basic web crawler providing a framework for crawling websites.
The `BasicCrawler` provides a low-level functionality for crawling websites, allowing users to define their
own page download and data extraction logic. It is designed mostly to be subclassed by crawlers with specific
purposes. In most cases, you will want to use a more specialized crawler, such as `HttpCrawler`,
`BeautifulSoupCrawler`, `ParselCrawler`, or `PlaywrightCrawler`. If you are an advanced user and want full
control over the crawling process, you can subclass the `BasicCrawler` and implement the request-handling logic
yourself.
The crawling process begins with URLs provided by a `RequestProvider` instance. Each request is then
handled by a user-defined `request_handler` function, which processes the page and extracts the data.
The `BasicCrawler` includes several common features for crawling, such as:
- automatic scaling based on the system resources,
- retries for failed requests,
- session management,
- statistics tracking,
- request routing via labels,
- proxy rotation,
- direct storage interaction helpers,
- and more.
"""
_CRAWLEE_STATE_KEY = 'CRAWLEE_STATE'
_request_handler_timeout_text = 'Request handler timed out after'
__next_id = 0
def __init__(
self,
*,
configuration: Configuration | None = None,
event_manager: EventManager | None = None,
storage_client: StorageClient | None = None,
request_manager: RequestManager | None = None,
session_pool: SessionPool | None = None,
proxy_configuration: ProxyConfiguration | None = None,
http_client: HttpClient | None = None,
request_handler: Callable[[TCrawlingContext], Awaitable[None]] | None = None,
max_request_retries: int = 3,
max_requests_per_crawl: int | None = None,
max_session_rotations: int = 10,
max_crawl_depth: int | None = None,
use_session_pool: bool = True,
retry_on_blocked: bool = True,
additional_http_error_status_codes: Iterable[int] | None = None,
ignore_http_error_status_codes: Iterable[int] | None = None,
concurrency_settings: ConcurrencySettings | None = None,
request_handler_timeout: timedelta = timedelta(minutes=1),
statistics: Statistics[TStatisticsState] | None = None,
abort_on_error: bool = False,
keep_alive: bool = False,
configure_logging: bool = True,
statistics_log_format: Literal['table', 'inline'] = 'table',
respect_robots_txt_file: bool = False,
status_message_logging_interval: timedelta = timedelta(seconds=10),
status_message_callback: Callable[[StatisticsState, StatisticsState | None, str], Awaitable[str | None]]
| None = None,
id: int | None = None,
_context_pipeline: ContextPipeline[TCrawlingContext] | None = None,
_additional_context_managers: Sequence[AbstractAsyncContextManager] | None = None,
_logger: logging.Logger | None = None,
) -> None:
"""Initialize a new instance.
Args:
configuration: The `Configuration` instance. Some of its properties are used as defaults for the crawler.
event_manager: The event manager for managing events for the crawler and all its components.
storage_client: The storage client for managing storages for the crawler and all its components.
request_manager: Manager of requests that should be processed by the crawler.
session_pool: A custom `SessionPool` instance, allowing the use of non-default configuration.
proxy_configuration: HTTP proxy configuration used when making requests.
http_client: HTTP client used by `BasicCrawlingContext.send_request` method.
request_handler: A callable responsible for handling requests.
max_request_retries: Specifies the maximum number of retries allowed for a request if its processing fails.
This includes retries due to navigation errors or errors thrown from user-supplied functions
(`request_handler`, `pre_navigation_hooks` etc.).
This limit does not apply to retries triggered by session rotation (see `max_session_rotations`).
max_requests_per_crawl: Maximum number of pages to open during a crawl. The crawl stops upon reaching
this limit. Setting this value can help avoid infinite loops in misconfigured crawlers. `None` means
no limit. Due to concurrency settings, the actual number of pages visited may slightly exceed
this value. If used together with `keep_alive`, then the crawler will be kept alive only until
`max_requests_per_crawl` is achieved.
max_session_rotations: Maximum number of session rotations per request. The crawler rotates the session
if a proxy error occurs or if the website blocks the request.
The session rotations are not counted towards the `max_request_retries` limit.
max_crawl_depth: Specifies the maximum crawl depth. If set, the crawler will stop processing links beyond
this depth. The crawl depth starts at 0 for initial requests and increases with each subsequent level
of links. Requests at the maximum depth will still be processed, but no new links will be enqueued
from those requests. If not set, crawling continues without depth restrictions.
use_session_pool: Enable the use of a session pool for managing sessions during crawling.
retry_on_blocked: If True, the crawler attempts to bypass bot protections automatically.
additional_http_error_status_codes: Additional HTTP status codes to treat as errors,
triggering automatic retries when encountered.
ignore_http_error_status_codes: HTTP status codes that are typically considered errors but should be treated
as successful responses.
concurrency_settings: Settings to fine-tune concurrency levels.
request_handler_timeout: Maximum duration allowed for a single request handler to run.
statistics: A custom `Statistics` instance, allowing the use of non-default configuration.
abort_on_error: If True, the crawler stops immediately when any request handler error occurs.
keep_alive: If True, it will keep crawler alive even if there are no requests in queue.
Use `crawler.stop()` to exit the crawler.
configure_logging: If True, the crawler will set up logging infrastructure automatically.
statistics_log_format: If 'table', displays crawler statistics as formatted tables in logs. If 'inline',
outputs statistics as plain text log messages.
respect_robots_txt_file: If set to `True`, the crawler will automatically try to fetch the robots.txt file
for each domain, and skip those that are not allowed. This also prevents disallowed URLs to be added
via `EnqueueLinksFunction`
status_message_logging_interval: Interval for logging the crawler status messages.
status_message_callback: Allows overriding the default status message. The default status message is
provided in the parameters. Returning `None` suppresses the status message.
id: Identifier used for crawler state tracking. Use the same id across multiple crawlers to share state
between them.
_context_pipeline: Enables extending the request lifecycle and modifying the crawling context.
Intended for use by subclasses rather than direct instantiation of `BasicCrawler`.
_additional_context_managers: Additional context managers used throughout the crawler lifecycle.
Intended for use by subclasses rather than direct instantiation of `BasicCrawler`.
_logger: A logger instance, typically provided by a subclass, for consistent logging labels.
Intended for use by subclasses rather than direct instantiation of `BasicCrawler`.
"""
if id is None:
self._id = BasicCrawler.__next_id
BasicCrawler.__next_id += 1
else:
self._id = id
implicit_event_manager_with_explicit_config = False
if not configuration:
configuration = service_locator.get_configuration()
elif not event_manager:
implicit_event_manager_with_explicit_config = True
if not storage_client:
storage_client = service_locator.get_storage_client()
if not event_manager:
event_manager = service_locator.get_event_manager()
self._service_locator = ServiceLocator(
configuration=configuration, storage_client=storage_client, event_manager=event_manager
)
config = self._service_locator.get_configuration()
# Core components
self._request_manager = request_manager
self._session_pool = session_pool or SessionPool()
self._proxy_configuration = proxy_configuration
self._additional_http_error_status_codes = (
set(additional_http_error_status_codes) if additional_http_error_status_codes else set()
)
self._ignore_http_error_status_codes = (
set(ignore_http_error_status_codes) if ignore_http_error_status_codes else set()
)
self._http_client = http_client or ImpitHttpClient()
# Request router setup
self._router: Router[TCrawlingContext] | None = None
if isinstance(cast('Router', request_handler), Router):
self._router = cast('Router[TCrawlingContext]', request_handler)
elif request_handler is not None:
self._router = None
self.router.default_handler(request_handler)
# Error, failed & skipped request handlers
self._error_handler: ErrorHandler[TCrawlingContext | BasicCrawlingContext] | None = None
self._failed_request_handler: FailedRequestHandler[TCrawlingContext | BasicCrawlingContext] | None = None
self._on_skipped_request: SkippedRequestCallback | None = None
self._abort_on_error = abort_on_error
# Crawler callbacks
self._status_message_callback = status_message_callback
# Context of each request with matching result of request handler.
# Inheritors can use this to override the result of individual request handler runs in `_run_request_handler`.
self._context_result_map = WeakKeyDictionary[BasicCrawlingContext, RequestHandlerRunResult]()
# Context pipeline
self._context_pipeline = (_context_pipeline or ContextPipeline()).compose(self._check_url_after_redirects) # ty: ignore[invalid-argument-type]
# Crawl settings
self._max_request_retries = max_request_retries
self._max_requests_per_crawl = max_requests_per_crawl
self._max_session_rotations = max_session_rotations
self._max_crawl_depth = max_crawl_depth
self._respect_robots_txt_file = respect_robots_txt_file
# Timeouts
self._request_handler_timeout = request_handler_timeout
self._internal_timeout = (
config.internal_timeout
if config.internal_timeout is not None
else max(2 * request_handler_timeout, timedelta(minutes=5))
)
# Retry and session settings
self._use_session_pool = use_session_pool
self._retry_on_blocked = retry_on_blocked
# Logging setup
if configure_logging:
root_logger = logging.getLogger()
configure_logger(root_logger, remove_old_handlers=True)
httpx_logger = logging.getLogger('httpx') # Silence HTTPX logger
httpx_logger.setLevel(logging.DEBUG if get_configured_log_level() <= logging.DEBUG else logging.WARNING)
self._logger = _logger or logging.getLogger(__name__)
if implicit_event_manager_with_explicit_config:
self._logger.warning(
'No event manager set, implicitly using event manager from global service_locator.'
'It is advised to explicitly set the event manager if explicit configuration is used as well.'
)
self._statistics_log_format = statistics_log_format
# Statistics
if statistics:
self._statistics = statistics
else:
async def persist_state_factory() -> KeyValueStore:
return await self.get_key_value_store()
self._statistics = cast(
'Statistics[TStatisticsState]',
Statistics.with_default_state(
persistence_enabled=True,
periodic_message_logger=self._logger,
statistics_log_format=self._statistics_log_format,
log_message='Current request statistics:',
persist_state_kvs_factory=persist_state_factory,
),
)
# Additional context managers to enter and exit
self._additional_context_managers = _additional_context_managers or []
# Internal, not explicitly configurable components
self._robots_txt_file_cache: LRUCache[str, RobotsTxtFile] = LRUCache(maxsize=1000)
self._robots_txt_lock = asyncio.Lock()
self._tld_extractor = TLDExtract(cache_dir=tempfile.TemporaryDirectory().name)
self._snapshotter = Snapshotter.from_config(config)
self._autoscaled_pool = AutoscaledPool(
system_status=SystemStatus(self._snapshotter),
concurrency_settings=concurrency_settings,
is_finished_function=self.__is_finished_function,
is_task_ready_function=self.__is_task_ready_function,
run_task_function=self.__run_task_function,
)
self._crawler_state_rec_task = RecurringTask(
func=self._crawler_state_task, delay=status_message_logging_interval
)
self._previous_crawler_state: TStatisticsState | None = None
# State flags
self._keep_alive = keep_alive
self._running = False
self._has_finished_before = False
self._failed = False
self._unexpected_stop = False
@property
def log(self) -> logging.Logger:
"""The logger used by the crawler."""
return self._logger
@property
def router(self) -> Router[TCrawlingContext]:
"""The `Router` used to handle each individual crawling request."""
if self._router is None:
self._router = Router[TCrawlingContext]()
return self._router
@router.setter
def router(self, router: Router[TCrawlingContext]) -> None:
if self._router is not None:
raise RuntimeError('A router is already set')
self._router = router
@property
def statistics(self) -> Statistics[TStatisticsState]:
"""Statistics about the current (or last) crawler run."""
return self._statistics
def stop(self, reason: str = 'Stop was called externally.') -> None:
"""Set flag to stop crawler.
This stops current crawler run regardless of whether all requests were finished.
Args:
reason: Reason for stopping that will be used in logs.
"""
self._logger.info(f'Crawler.stop() was called with following reason: {reason}.')
self._unexpected_stop = True
def _wrap_handler_with_error_context(
self, handler: Callable[[TCrawlingContext | BasicCrawlingContext, Exception], Awaitable[T]]
) -> Callable[[TCrawlingContext | BasicCrawlingContext, Exception], Awaitable[T]]:
"""Decorate error handlers to make their context helpers usable."""
@functools.wraps(handler)
async def wrapped_handler(context: TCrawlingContext | BasicCrawlingContext, exception: Exception) -> T:
# Original context helpers that are from `RequestHandlerRunResult` will not be committed as the request
# failed. Modified context provides context helpers with direct access to the storages.
error_context = context.create_modified_copy(
push_data=self._push_data,
get_key_value_store=self.get_key_value_store,
add_requests=functools.partial(self._add_requests, context),
)
return await handler(error_context, exception)
return wrapped_handler
def _stop_if_max_requests_count_exceeded(self) -> None:
"""Call `stop` when the maximum number of requests to crawl has been reached."""
if self._max_requests_per_crawl is None:
return
if self._statistics.state.requests_total >= self._max_requests_per_crawl:
self.stop(
reason=f'The crawler has reached its limit of {self._max_requests_per_crawl} requests per crawl. '
)
async def _get_session(self) -> Session | None:
"""If session pool is being used, try to take a session from it."""
if not self._use_session_pool:
return None
return await wait_for(
self._session_pool.get_session,
timeout=self._internal_timeout,
timeout_message='Fetching a session from the pool timed out after '
f'{self._internal_timeout.total_seconds()} seconds',
max_retries=3,
logger=self._logger,
)
async def _get_session_by_id(self, session_id: str | None) -> Session | None:
"""If session pool is being used, try to take a session by id from it."""
if not self._use_session_pool or not session_id:
return None
return await wait_for(
partial(self._session_pool.get_session_by_id, session_id),
timeout=self._internal_timeout,
timeout_message='Fetching a session from the pool timed out after '
f'{self._internal_timeout.total_seconds()} seconds',
max_retries=3,
logger=self._logger,
)
async def _get_proxy_info(self, request: Request, session: Session | None) -> ProxyInfo | None:
"""Retrieve a new ProxyInfo object based on crawler configuration and the current request and session."""
if not self._proxy_configuration:
return None
return await self._proxy_configuration.new_proxy_info(
session_id=session.id if session else None,
request=request,
proxy_tier=None,
)
async def get_request_manager(self) -> RequestManager:
"""Return the configured request manager. If none is configured, open and return the default request queue."""
if not self._request_manager:
self._request_manager = await RequestQueue.open(
storage_client=self._service_locator.get_storage_client(),
configuration=self._service_locator.get_configuration(),
)
return self._request_manager
async def get_dataset(
self,
*,
id: str | None = None,
name: str | None = None,
alias: str | None = None,
) -> Dataset:
"""Return the `Dataset` with the given ID or name. If none is provided, return the default one."""
return await Dataset.open(
id=id,
name=name,
alias=alias,
storage_client=self._service_locator.get_storage_client(),
configuration=self._service_locator.get_configuration(),
)
async def get_key_value_store(
self,
*,
id: str | None = None,
name: str | None = None,
alias: str | None = None,
) -> KeyValueStore:
"""Return the `KeyValueStore` with the given ID or name. If none is provided, return the default KVS."""
return await KeyValueStore.open(
id=id,
name=name,
alias=alias,
storage_client=self._service_locator.get_storage_client(),
configuration=self._service_locator.get_configuration(),
)
def error_handler(
self, handler: ErrorHandler[TCrawlingContext | BasicCrawlingContext]
) -> ErrorHandler[TCrawlingContext]:
"""Register a function to handle errors occurring in request handlers.
The error handler is invoked after a request handler error occurs and before a retry attempt.
"""
self._error_handler = self._wrap_handler_with_error_context(handler)
return handler
def failed_request_handler(
self, handler: FailedRequestHandler[TCrawlingContext | BasicCrawlingContext]
) -> FailedRequestHandler[TCrawlingContext]:
"""Register a function to handle requests that exceed the maximum retry limit.
The failed request handler is invoked when a request has failed all retry attempts.
"""
self._failed_request_handler = self._wrap_handler_with_error_context(handler)
return handler
def on_skipped_request(self, callback: SkippedRequestCallback) -> SkippedRequestCallback:
"""Register a function to handle skipped requests.
The skipped request handler is invoked when a request is skipped due to a collision or other reasons.
"""
self._on_skipped_request = callback
return callback
async def run(
self,
requests: Sequence[str | Request] | None = None,
*,
purge_request_queue: bool = True,
) -> FinalStatistics:
"""Run the crawler until all requests are processed.
Args:
requests: The requests to be enqueued before the crawler starts.
purge_request_queue: If this is `True` and the crawler is not being run for the first time, the default
request queue will be purged.
"""
if self._running:
raise RuntimeError(
'This crawler instance is already running, you can add more requests to it via `crawler.add_requests()`'
)
self._running = True
if self._has_finished_before:
await self._statistics.reset()
if self._use_session_pool:
await self._session_pool.reset_store()
request_manager = await self.get_request_manager()
if purge_request_queue and isinstance(request_manager, RequestQueue):
await request_manager.drop()
self._request_manager = await RequestQueue.open(
storage_client=self._service_locator.get_storage_client(),
configuration=self._service_locator.get_configuration(),
)
if requests is not None:
await self.add_requests(requests)
interrupted = False
def sigint_handler() -> None:
nonlocal interrupted
if not interrupted:
interrupted = True
self._logger.info('Pausing... Press CTRL+C again to force exit.')
run_task.cancel()
run_task = asyncio.create_task(self._run_crawler(), name='run_crawler_task')
if threading.current_thread() is threading.main_thread(): # `add_signal_handler` works only in the main thread
with suppress(NotImplementedError): # event loop signal handlers are not supported on Windows
asyncio.get_running_loop().add_signal_handler(signal.SIGINT, sigint_handler)
try:
await run_task
except CancelledError:
pass
finally:
if threading.current_thread() is threading.main_thread():
with suppress(NotImplementedError):
asyncio.get_running_loop().remove_signal_handler(signal.SIGINT)
if self._statistics.error_tracker.total > 0:
self._logger.info(
'Error analysis:'
f' total_errors={self._statistics.error_tracker.total}'
f' unique_errors={self._statistics.error_tracker.unique_error_count}'
)
if interrupted:
self._logger.info(
f'The crawl was interrupted. To resume, do: CRAWLEE_PURGE_ON_START=0 python {sys.argv[0]}'
)
self._running = False
self._has_finished_before = True
await self._save_crawler_state()
final_statistics = self._statistics.calculate()
if self._statistics_log_format == 'table':
self._logger.info(f'Final request statistics:\n{final_statistics.to_table()}')
else:
self._logger.info('Final request statistics:', extra=final_statistics.to_dict())
return final_statistics
async def _run_crawler(self) -> None:
event_manager = self._service_locator.get_event_manager()
# Collect the context managers to be entered. Context managers that are already active are excluded,
# as they were likely entered by the caller, who will also be responsible for exiting them.
contexts_to_enter = [
cm
for cm in (
event_manager,
self._snapshotter,
self._statistics,
self._session_pool if self._use_session_pool else None,
self._http_client,
self._crawler_state_rec_task,
*self._additional_context_managers,
)
if cm and getattr(cm, 'active', False) is False
]
async with AsyncExitStack() as exit_stack:
for context in contexts_to_enter:
await exit_stack.enter_async_context(context) # ty: ignore[invalid-argument-type]
await self._autoscaled_pool.run()
async def add_requests(
self,
requests: Sequence[str | Request],
*,
forefront: bool = False,
batch_size: int = 1000,
wait_time_between_batches: timedelta = timedelta(0),
wait_for_all_requests_to_be_added: bool = False,
wait_for_all_requests_to_be_added_timeout: timedelta | None = None,
) -> None:
"""Add requests to the underlying request manager in batches.
Args:
requests: A list of requests to add to the queue.
forefront: If True, add requests to the forefront of the queue.
batch_size: The number of requests to add in one batch.
wait_time_between_batches: Time to wait between adding batches.
wait_for_all_requests_to_be_added: If True, wait for all requests to be added before returning.
wait_for_all_requests_to_be_added_timeout: Timeout for waiting for all requests to be added.
"""
allowed_requests = []
skipped = []
for request in requests:
check_url = request.url if isinstance(request, Request) else request
if await self._is_allowed_based_on_robots_txt_file(check_url):
allowed_requests.append(request)
else:
skipped.append(request)
if skipped:
skipped_tasks = [
asyncio.create_task(self._handle_skipped_request(request, 'robots_txt')) for request in skipped
]
await asyncio.gather(*skipped_tasks)
self._logger.warning('Some requests were skipped because they were disallowed based on the robots.txt file')
request_manager = await self.get_request_manager()
await request_manager.add_requests(
requests=allowed_requests,
forefront=forefront,
batch_size=batch_size,
wait_time_between_batches=wait_time_between_batches,
wait_for_all_requests_to_be_added=wait_for_all_requests_to_be_added,
wait_for_all_requests_to_be_added_timeout=wait_for_all_requests_to_be_added_timeout,
)
async def _use_state(
self,
default_value: dict[str, JsonSerializable] | None = None,
) -> dict[str, JsonSerializable]:
kvs = await self.get_key_value_store()
return await kvs.get_auto_saved_value(f'{self._CRAWLEE_STATE_KEY}_{self._id}', default_value)
async def _save_crawler_state(self) -> None:
store = await self.get_key_value_store()
await store.persist_autosaved_values()
async def get_data(
self,
dataset_id: str | None = None,
dataset_name: str | None = None,
dataset_alias: str | None = None,
**kwargs: Unpack[GetDataKwargs],
) -> DatasetItemsListPage:
"""Retrieve data from a `Dataset`.
This helper method simplifies the process of retrieving data from a `Dataset`. It opens the specified
one and then retrieves the data based on the provided parameters.
Args:
dataset_id: The ID of the `Dataset`.
dataset_name: The name of the `Dataset` (global scope, named storage).
dataset_alias: The alias of the `Dataset` (run scope, unnamed storage).
kwargs: Keyword arguments to be passed to the `Dataset.get_data()` method.
Returns:
The retrieved data.
"""
dataset = await Dataset.open(
id=dataset_id,
name=dataset_name,
alias=dataset_alias,
storage_client=self._service_locator.get_storage_client(),
configuration=self._service_locator.get_configuration(),
)
return await dataset.get_data(**kwargs)
async def export_data(
self,
path: str | Path,
dataset_id: str | None = None,
dataset_name: str | None = None,
dataset_alias: str | None = None,
**additional_kwargs: Unpack[ExportDataJsonKwargs | ExportDataCsvKwargs],
) -> None:
"""Export all items from a Dataset to a JSON or CSV file.
This method simplifies the process of exporting data collected during crawling. It automatically
determines the export format based on the file extension (`.json` or `.csv`) and handles
the conversion of `Dataset` items to the appropriate format.
Args:
path: The destination file path. Must end with '.json' or '.csv'.
dataset_id: The ID of the Dataset to export from.
dataset_name: The name of the Dataset to export from (global scope, named storage).
dataset_alias: The alias of the Dataset to export from (run scope, unnamed storage).
additional_kwargs: Extra keyword arguments forwarded to the JSON/CSV exporter depending on the file format.
"""
dataset = await Dataset.open(
id=dataset_id,
name=dataset_name,
alias=dataset_alias,
storage_client=self._service_locator.get_storage_client(),
configuration=self._service_locator.get_configuration(),
)
path = Path(path)
if path.suffix == '.csv':
dst = StringIO()
csv_kwargs = cast('ExportDataCsvKwargs', additional_kwargs)
await export_csv_to_stream(dataset.iterate_items(), dst, **csv_kwargs)
await atomic_write(path, dst.getvalue())
elif path.suffix == '.json':
dst = StringIO()
json_kwargs = cast('ExportDataJsonKwargs', additional_kwargs)
await export_json_to_stream(dataset.iterate_items(), dst, **json_kwargs)
await atomic_write(path, dst.getvalue())
else:
raise ValueError(f'Unsupported file extension: {path.suffix}')
async def _push_data(
self,
data: list[dict[str, Any]] | dict[str, Any],
dataset_id: str | None = None,
dataset_name: str | None = None,
dataset_alias: str | None = None,
**kwargs: Unpack[PushDataKwargs],
) -> None:
"""Push data to a `Dataset`.
This helper method simplifies the process of pushing data to a `Dataset`. It opens the specified
one and then pushes the provided data to it.
Args:
data: The data to push to the `Dataset`.
dataset_id: The ID of the `Dataset`.
dataset_name: The name of the `Dataset` (global scope, named storage).
dataset_alias: The alias of the `Dataset` (run scope, unnamed storage).
kwargs: Keyword arguments to be passed to the `Dataset.push_data()` method.
"""
dataset = await self.get_dataset(id=dataset_id, name=dataset_name, alias=dataset_alias)
await dataset.push_data(data, **kwargs)
def _should_retry_request(self, context: BasicCrawlingContext, error: Exception) -> bool:
if context.request.no_retry:
return False
# Do not retry on client errors.
if isinstance(error, HttpClientStatusCodeError):
return False
if isinstance(error, SessionError):
return ((context.request.session_rotation_count or 0) + 1) < self._max_session_rotations
max_request_retries = context.request.max_retries
if max_request_retries is None:
max_request_retries = self._max_request_retries
return context.request.retry_count < max_request_retries
async def _check_url_after_redirects(self, context: TCrawlingContext) -> AsyncGenerator[TCrawlingContext, None]:
"""Ensure that the `loaded_url` still matches the enqueue strategy after redirects.
Filter out links that redirect outside of the crawled domain.
"""
if context.request.loaded_url is not None and not self._check_enqueue_strategy(
context.request.enqueue_strategy,
origin_url=urlparse(context.request.url),
target_url=urlparse(context.request.loaded_url),
):
raise ContextPipelineInterruptedError(
f'Skipping URL {context.request.loaded_url} (redirected from {context.request.url})'
)
yield context
def _create_enqueue_links_function(
self, context: BasicCrawlingContext, extract_links: ExtractLinksFunction
) -> EnqueueLinksFunction:
"""Create a callback function for extracting links from parsed content and enqueuing them to the crawl.
Args:
context: The current crawling context.
extract_links: Function used to extract links from the page.
Returns:
Awaitable that is used for extracting links from parsed content and enqueuing them to the crawl.
"""
async def enqueue_links(
*,
selector: str | None = None,
attribute: str | None = None,