-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathbasic-crawler.ts
More file actions
2377 lines (2040 loc) · 98.3 KB
/
basic-crawler.ts
File metadata and controls
2377 lines (2040 loc) · 98.3 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
import { writeFile } from 'node:fs/promises';
import { dirname } from 'node:path';
import type {
AddRequestsBatchedOptions,
AddRequestsBatchedResult,
AutoscaledPoolOptions,
Configuration,
CrawleeLogger,
CrawlingContext,
DatasetExportOptions,
EnqueueLinksOptions,
EventManager,
FinalStatistics,
GetUserDataFromRequest,
IRequestList,
IRequestManager,
ProxyConfiguration,
Request,
RequestsLike,
RequestTransform,
RouterHandler,
RouterRoutes,
SkippedRequestCallback,
Source,
StatisticsOptions,
StatisticState,
StorageIdentifier,
} from '@crawlee/core';
import {
AutoscaledPool,
bindMethodsToServiceLocator,
BLOCKED_STATUS_CODES,
ContextPipeline,
ContextPipelineCleanupError,
ContextPipelineInitializationError,
ContextPipelineInterruptedError,
CriticalError,
Dataset,
enqueueLinks,
EnqueueStrategy,
EventType,
KeyValueStore,
LogLevel,
mergeCookies,
MissingSessionError,
NavigationSkippedError,
NonRetryableError,
purgeDefaultStorages,
RequestHandlerError,
RequestListAdapter,
RequestManagerTandem,
RequestProvider,
RequestQueue,
RequestQueueV1,
RequestState,
RetryRequestError,
Router,
ServiceLocator,
serviceLocator,
Session,
SessionError,
SessionPool,
Statistics,
validators,
} from '@crawlee/core';
import { GotScrapingHttpClient } from '@crawlee/got-scraping-client';
import type {
Awaitable,
BaseHttpClient,
BatchAddRequestsResult,
Dictionary,
ISession,
ISessionPool,
ProxyInfo,
SetStatusMessageOptions,
StorageClient,
} from '@crawlee/types';
import { getObjectType, isAsyncIterable, isIterable, RobotsTxtFile, ROTATE_PROXY_ERRORS } from '@crawlee/utils';
import { stringify } from 'csv-stringify/sync';
import { ensureDir, writeJSON } from 'fs-extra/esm';
import ow from 'ow';
import { getDomain } from 'tldts';
import type { ReadonlyDeep, SetRequired } from 'type-fest';
import { LruCache } from '@apify/datastructures';
import { addTimeoutToPromise, TimeoutError } from '@apify/timeout';
import { cryptoRandomObjectId } from '@apify/utilities';
import { createSendRequest } from './send-request.js';
export interface BasicCrawlingContext<UserData extends Dictionary = Dictionary> extends CrawlingContext<UserData> {}
/**
* Since there's no set number of seconds before the container is terminated after
* a migration event, we need some reasonable number to use for RequestList persistence.
* Once a migration event is received, the crawler will be paused, and it will wait for
* this long before persisting the RequestList state. This should allow most healthy
* requests to finish and be marked as handled, thus lowering the amount of duplicate
* results after migration.
* @ignore
*/
const SAFE_MIGRATION_WAIT_MILLIS = 20000;
const deferredCleanupKey = Symbol('deferredCleanup');
export type RequestHandler<Context extends CrawlingContext = CrawlingContext> = (inputs: Context) => Awaitable<void>;
export type ErrorHandler<
Context extends CrawlingContext = CrawlingContext,
ExtendedContext extends Context = Context,
> = (inputs: Context & Partial<ExtendedContext>, error: Error) => Awaitable<void>;
export interface StatusMessageCallbackParams<
Context extends CrawlingContext = BasicCrawlingContext,
Crawler extends BasicCrawler<any> = BasicCrawler<Context>,
> {
state: StatisticState;
crawler: Crawler;
previousState: StatisticState;
message: string;
}
export type StatusMessageCallback<
Context extends CrawlingContext = BasicCrawlingContext,
Crawler extends BasicCrawler<any> = BasicCrawler<Context>,
> = (params: StatusMessageCallbackParams<Context, Crawler>) => Awaitable<void>;
export type RequireContextPipeline<
DefaultContextType extends CrawlingContext,
FinalContextType extends DefaultContextType,
> = DefaultContextType extends FinalContextType
? {}
: { contextPipelineBuilder: () => ContextPipeline<CrawlingContext, FinalContextType> };
export interface BasicCrawlerOptions<
Context extends CrawlingContext = CrawlingContext,
ContextExtension = Dictionary<never>,
ExtendedContext extends Context = Context & ContextExtension,
> {
/**
* User-provided function that performs the logic of the crawler. It is called for each URL to crawl.
*
* The function receives the {@apilink BasicCrawlingContext} as an argument,
* where the {@apilink BasicCrawlingContext.request|`request`} represents the URL to crawl.
*
* The function must return a promise, which is then awaited by the crawler.
*
* If the function throws an exception, the crawler will try to re-crawl the
* request later, up to the {@apilink BasicCrawlerOptions.maxRequestRetries|`maxRequestRetries`} times.
* If all the retries fail, the crawler calls the function
* provided to the {@apilink BasicCrawlerOptions.failedRequestHandler|`failedRequestHandler`} parameter.
* To make this work, we should **always**
* let our function throw exceptions rather than catch them.
* The exceptions are logged to the request using the
* {@apilink Request.pushErrorMessage|`Request.pushErrorMessage()`} function.
*/
requestHandler?: RequestHandler<ExtendedContext>;
/**
* Allows the user to extend the crawling context passed to the request handler with custom functionality.
*
* **Example usage:**
*
* ```javascript
* import { BasicCrawler } from 'crawlee';
*
* // Create a crawler instance
* const crawler = new BasicCrawler({
* extendContext(context) => ({
* async customHelper() {
* await context.pushData({ url: context.request.url })
* }
* }),
* async requestHandler(context) {
* await context.customHelper();
* },
* });
* ```
*/
extendContext?: (context: Context) => Awaitable<ContextExtension>;
/**
* *Intended for BasicCrawler subclasses*. Prepares a context pipeline that transforms the initial crawling context into the shape given by the `Context` type parameter.
*
* The option is not required if your crawler subclass does not extend the crawling context with custom information or helpers.
*/
contextPipelineBuilder?: () => ContextPipeline<CrawlingContext, Context>;
/**
* Static list of URLs to be processed.
* If not provided, the crawler will open the default request queue when the {@apilink BasicCrawler.addRequests|`crawler.addRequests()`} function is called.
* > Alternatively, `requests` parameter of {@apilink BasicCrawler.run|`crawler.run()`} could be used to enqueue the initial requests -
* it is a shortcut for running `crawler.addRequests()` before the `crawler.run()`.
*/
requestList?: IRequestList;
/**
* Dynamic queue of URLs to be processed. This is useful for recursive crawling of websites.
* If not provided, the crawler will open the default request queue when the {@apilink BasicCrawler.addRequests|`crawler.addRequests()`} function is called.
* > Alternatively, `requests` parameter of {@apilink BasicCrawler.run|`crawler.run()`} could be used to enqueue the initial requests -
* it is a shortcut for running `crawler.addRequests()` before the `crawler.run()`.
*/
requestQueue?: RequestProvider;
/**
* Allows explicitly configuring a request manager. Mutually exclusive with the `requestQueue` and `requestList` options.
*
* This enables explicitly configuring the crawler to use `RequestManagerTandem`, for instance.
* If using this, the type of `BasicCrawler.requestQueue` may not be fully compatible with the `RequestProvider` class.
*/
requestManager?: IRequestManager;
/**
* Timeout in which the function passed as {@apilink BasicCrawlerOptions.requestHandler|`requestHandler`} needs to finish, in seconds.
* @default 60
*/
requestHandlerTimeoutSecs?: number;
/**
* User-provided function that allows modifying the request object before it gets retried by the crawler.
* It's executed before each retry for the requests that failed less than {@apilink BasicCrawlerOptions.maxRequestRetries|`maxRequestRetries`} times.
*
* The function receives the {@apilink BasicCrawlingContext} as the first argument,
* where the {@apilink BasicCrawlingContext.request|`request`} corresponds to the request to be retried.
* Second argument is the `Error` instance that
* represents the last error thrown during processing of the request.
*/
errorHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;
/**
* A function to handle requests that failed more than {@apilink BasicCrawlerOptions.maxRequestRetries|`maxRequestRetries`} times.
*
* The function receives the {@apilink BasicCrawlingContext} as the first argument,
* where the {@apilink BasicCrawlingContext.request|`request`} corresponds to the failed request.
* Second argument is the `Error` instance that
* represents the last error thrown during processing of the request.
*/
failedRequestHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;
/**
* Specifies the maximum number of retries allowed for a request if its processing fails.
* This includes retries due to navigation errors, session/proxy errors, or errors thrown from user-supplied
* functions (`requestHandler`, `preNavigationHooks`, `postNavigationHooks`).
* @default 3
*/
maxRequestRetries?: number;
/**
* Indicates how much time (in seconds) to wait before crawling another same domain request.
* @default 0
*/
sameDomainDelaySecs?: number;
/**
* Maximum number of pages that the crawler will open. The crawl will stop when this limit is reached.
* This value should always be set in order to prevent infinite loops in misconfigured crawlers.
* > *NOTE:* In cases of parallel crawling, the actual number of pages visited might be slightly higher than this value.
*/
maxRequestsPerCrawl?: number;
/**
* Maximum depth of the crawl. If not set, the crawl will continue until all requests are processed.
* Setting this to `0` will only process the initial requests, skipping all links enqueued by `crawlingContext.enqueueLinks` and `crawlingContext.addRequests`.
* Passing `1` will process the initial requests and all links enqueued by `crawlingContext.enqueueLinks` and `crawlingContext.addRequests` in the handler for initial requests.
*/
maxCrawlDepth?: number;
/**
* Custom options passed to the underlying {@apilink AutoscaledPool} constructor.
* > *NOTE:* The {@apilink AutoscaledPoolOptions.runTaskFunction|`runTaskFunction`}
* option is provided by the crawler and cannot be overridden.
* However, we can provide custom implementations of {@apilink AutoscaledPoolOptions.isFinishedFunction|`isFinishedFunction`}
* and {@apilink AutoscaledPoolOptions.isTaskReadyFunction|`isTaskReadyFunction`}.
*/
autoscaledPoolOptions?: AutoscaledPoolOptions;
/**
* Sets the minimum concurrency (parallelism) for the crawl. Shortcut for the
* AutoscaledPool {@apilink AutoscaledPoolOptions.minConcurrency|`minConcurrency`} option.
* > *WARNING:* If we set this value too high with respect to the available system memory and CPU, our crawler will run extremely slow or crash.
* If not sure, it's better to keep the default value and the concurrency will scale up automatically.
*/
minConcurrency?: number;
/**
* Sets the maximum concurrency (parallelism) for the crawl. Shortcut for the
* AutoscaledPool {@apilink AutoscaledPoolOptions.maxConcurrency|`maxConcurrency`} option.
*/
maxConcurrency?: number;
/**
* The maximum number of requests per minute the crawler should run.
* By default, this is set to `Infinity`, but we can pass any positive, non-zero integer.
* Shortcut for the AutoscaledPool {@apilink AutoscaledPoolOptions.maxTasksPerMinute|`maxTasksPerMinute`} option.
*/
maxRequestsPerMinute?: number;
/**
* Allows to keep the crawler alive even if the {@apilink RequestQueue} gets empty.
* By default, the `crawler.run()` will resolve once the queue is empty. With `keepAlive: true` it will keep running,
* waiting for more requests to come. Use `crawler.stop()` to exit the crawler gracefully, or `crawler.teardown()` to stop it immediately.
*/
keepAlive?: boolean;
/**
* An existing session pool instance to use. When provided, the crawler will use this pool directly instead of
* creating a new one, enabling session sharing across multiple crawlers. The crawler will not tear down a shared
* pool — the caller is responsible for its lifecycle.
*
* Accepts the built-in {@apilink SessionPool} or any object implementing the {@apilink ISessionPool} interface,
* so custom session-management strategies can be plugged in.
*/
sessionPool?: ISessionPool;
/**
* Defines the length of the interval for calling the `setStatusMessage` in seconds.
*/
statusMessageLoggingInterval?: number;
/**
* Allows overriding the default status message. The callback needs to call `crawler.setStatusMessage()` explicitly.
* The default status message is provided in the parameters.
*
* ```ts
* const crawler = new CheerioCrawler({
* statusMessageCallback: async (ctx) => {
* return ctx.crawler.setStatusMessage(`this is status message from ${new Date().toISOString()}`, { level: 'INFO' }); // log level defaults to 'DEBUG'
* },
* statusMessageLoggingInterval: 1, // defaults to 10s
* async requestHandler({ $, enqueueLinks, request, log }) {
* // ...
* },
* });
* ```
*/
statusMessageCallback?: StatusMessageCallback;
/**
* HTTP status codes that indicate the session should be retired.
* @default [401, 403, 429]
*/
blockedStatusCodes?: number[];
/**
* If set to `true`, the crawler will automatically try to bypass any detected bot protection.
*
* Currently supports:
* - [**Cloudflare** Bot Management](https://www.cloudflare.com/products/bot-management/)
* - [**Google Search** Rate Limiting](https://www.google.com/sorry/)
*/
retryOnBlocked?: boolean;
/**
* 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 `enqueueLinks`.
*
* If an object is provided, it may contain a `userAgent` property to specify which user-agent
* should be used when checking the robots.txt file. If not provided, the default user-agent `*` will be used.
*/
respectRobotsTxtFile?: boolean | { userAgent?: string };
/**
* When a request is skipped for some reason, you can use this callback to act on it.
* This is currently fired for requests skipped
* 1. based on robots.txt file,
* 2. because they don't match enqueueLinks filters,
* 3. because they are redirected to a URL that doesn't match the enqueueLinks strategy,
* 4. or because the {@apilink BasicCrawlerOptions.maxRequestsPerCrawl|`maxRequestsPerCrawl`} limit has been reached
*/
onSkippedRequest?: SkippedRequestCallback;
/**
* Enables experimental features of Crawlee, which can alter the behavior of the crawler.
* WARNING: these options are not guaranteed to be stable and may change or be removed at any time.
*/
experiments?: CrawlerExperiments;
/**
* Customize the way statistics collecting works, such as logging interval or
* whether to output them to the Key-Value store.
*/
statisticsOptions?: StatisticsOptions;
/**
* HTTP client implementation for the `sendRequest` context helper and for plain HTTP crawling.
* Defaults to a new instance of {@apilink GotScrapingHttpClient}
*/
httpClient?: BaseHttpClient;
/**
* If set, the crawler will be configured for all connections to use
* the Proxy URLs provided and rotated according to the configuration.
*/
proxyConfiguration?: ProxyConfiguration;
/**
* Custom configuration to use for this crawler.
* If provided, the crawler will use its own ServiceLocator instance instead of the global one.
*/
configuration?: Configuration;
/**
* Custom storage client to use for this crawler.
* If provided, the crawler will use its own ServiceLocator instance instead of the global one.
*/
storageClient?: StorageClient;
/**
* Custom event manager to use for this crawler.
* If provided, the crawler will use its own ServiceLocator instance instead of the global one.
*/
eventManager?: EventManager;
/**
* Custom logger to use for this crawler.
* If provided, the crawler will use its own ServiceLocator instance instead of the global one.
*/
logger?: CrawleeLogger;
/**
* A unique identifier for the crawler instance. This ID is used to isolate the state returned by
* {@apilink BasicCrawler.useState|`crawler.useState()`} from other crawler instances.
*
* When multiple crawler instances use `useState()` without an explicit `id`, they will share the same
* state object for backward compatibility. A warning will be logged in this case.
*
* To ensure each crawler has its own isolated state that also persists across script restarts
* (e.g., during Apify migrations), provide a stable, unique ID for each crawler instance.
*
*/
id?: string;
/**
* An array of HTTP response [Status Codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) to be excluded from error consideration.
* By default, status codes >= 500 trigger errors.
*/
ignoreHttpErrorStatusCodes?: number[];
/**
* An array of additional HTTP response [Status Codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) to be treated as errors.
* By default, status codes >= 500 trigger errors.
*/
additionalHttpErrorStatusCodes?: number[];
}
/**
* A set of options that you can toggle to enable experimental features in Crawlee.
*
* NOTE: These options will not respect semantic versioning and may be removed or changed at any time. Use at your own risk.
* If you do use these and encounter issues, please report them to us.
*/
export interface CrawlerExperiments {
/**
* @deprecated This experiment is now enabled by default, and this flag will be removed in a future release.
* If you encounter issues due to this change, please:
* - report it to us: https://github.com/apify/crawlee
* - set `requestLocking` to `false` in the `experiments` option of the crawler
*/
requestLocking?: boolean;
}
/**
* Provides a simple framework for parallel crawling of web pages.
* The URLs to crawl are fed either from a static list of URLs
* or from a dynamic queue of URLs enabling recursive crawling of websites.
*
* `BasicCrawler` is a low-level tool that requires the user to implement the page
* download and data extraction functionality themselves.
* If we want a crawler that already facilitates this functionality,
* we should consider using {@apilink CheerioCrawler}, {@apilink PuppeteerCrawler} or {@apilink PlaywrightCrawler}.
*
* `BasicCrawler` invokes the user-provided {@apilink BasicCrawlerOptions.requestHandler|`requestHandler`}
* for each {@apilink Request} object, which represents a single URL to crawl.
* The {@apilink Request} objects are fed from the {@apilink RequestList} or {@apilink RequestQueue}
* instances provided by the {@apilink BasicCrawlerOptions.requestList|`requestList`} or {@apilink BasicCrawlerOptions.requestQueue|`requestQueue`}
* constructor options, respectively. If neither `requestList` nor `requestQueue` options are provided,
* the crawler will open the default request queue either when the {@apilink BasicCrawler.addRequests|`crawler.addRequests()`} function is called,
* or if `requests` parameter (representing the initial requests) of the {@apilink BasicCrawler.run|`crawler.run()`} function is provided.
*
* If both {@apilink BasicCrawlerOptions.requestList|`requestList`} and {@apilink BasicCrawlerOptions.requestQueue|`requestQueue`} options are used,
* the instance first processes URLs from the {@apilink RequestList} and automatically enqueues all of them
* to the {@apilink RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.
*
* The crawler finishes if there are no more {@apilink Request} objects to crawl.
*
* New requests are only dispatched when there is enough free CPU and memory available,
* using the functionality provided by the {@apilink AutoscaledPool} class.
* All {@apilink AutoscaledPool} configuration options can be passed to the {@apilink BasicCrawlerOptions.autoscaledPoolOptions|`autoscaledPoolOptions`}
* parameter of the `BasicCrawler` constructor.
* For user convenience, the {@apilink AutoscaledPoolOptions.minConcurrency|`minConcurrency`} and
* {@apilink AutoscaledPoolOptions.maxConcurrency|`maxConcurrency`} options of the
* underlying {@apilink AutoscaledPool} constructor are available directly in the `BasicCrawler` constructor.
*
* **Example usage:**
*
* ```javascript
* import { BasicCrawler, Dataset } from 'crawlee';
*
* // Create a crawler instance
* const crawler = new BasicCrawler({
* async requestHandler({ request, sendRequest }) {
* // 'request' contains an instance of the Request class
* // Here we simply fetch the HTML of the page and store it to a dataset
* const { body } = await sendRequest({
* url: request.url,
* method: request.method,
* body: request.payload,
* headers: request.headers,
* });
*
* await Dataset.pushData({
* url: request.url,
* html: body,
* })
* },
* });
*
* // Enqueue the initial requests and run the crawler
* await crawler.run([
* 'http://www.example.com/page-1',
* 'http://www.example.com/page-2',
* ]);
* ```
* @category Crawlers
*/
export class BasicCrawler<
Context extends CrawlingContext = CrawlingContext,
ContextExtension = Dictionary<never>,
ExtendedContext extends Context = Context & ContextExtension,
> {
protected static readonly CRAWLEE_STATE_KEY = 'CRAWLEE_STATE';
/**
* Tracks crawler instances that accessed shared state without having an explicit id.
* Used to detect and warn about multiple crawlers sharing the same state.
*/
private static useStateCrawlerIds = new Set<string>();
/**
* A reference to the underlying {@apilink Statistics} class that collects and logs run statistics for requests.
*/
readonly stats: Statistics;
/**
* A reference to the underlying {@apilink RequestList} class that manages the crawler's {@apilink Request|requests}.
* Only available if used by the crawler.
*/
requestList?: IRequestList;
/**
* Dynamic queue of URLs to be processed. This is useful for recursive crawling of websites.
* A reference to the underlying {@apilink RequestQueue} class that manages the crawler's {@apilink Request|requests}.
* Only available if used by the crawler.
*/
requestQueue?: RequestProvider;
/**
* The main request-handling component of the crawler. It's initialized during the crawler startup.
*/
protected requestManager?: IRequestManager;
/**
* A reference to the underlying session pool that manages the crawler's {@apilink Session|sessions}. Typed as
* {@apilink ISessionPool} so custom implementations can be plugged in via the `sessionPool` constructor option.
*/
sessionPool: ISessionPool;
/**
* Set when the crawler constructed its own {@apilink SessionPool} (no `sessionPool` option was provided).
* Holds the same instance as `sessionPool`, but typed as the concrete class so the crawler can call
* lifecycle methods (`resetStore`, `teardown`) that aren't part of {@apilink ISessionPool}. A user-supplied
* pool is never owned and never torn down by the crawler.
*/
private ownedSessionPool?: SessionPool;
/**
* A reference to the underlying {@apilink AutoscaledPool} class that manages the concurrency of the crawler.
* > *NOTE:* This property is only initialized after calling the {@apilink BasicCrawler.run|`crawler.run()`} function.
* We can use it to change the concurrency settings on the fly,
* to pause the crawler by calling {@apilink AutoscaledPool.pause|`autoscaledPool.pause()`}
* or to abort it by calling {@apilink AutoscaledPool.abort|`autoscaledPool.abort()`}.
*/
autoscaledPool?: AutoscaledPool;
/**
* A reference to the underlying {@apilink ProxyConfiguration} class that manages the crawler's proxies.
* Only available if used by the crawler.
*/
proxyConfiguration?: ProxyConfiguration;
/**
* Default {@apilink Router} instance that will be used if we don't specify any {@apilink BasicCrawlerOptions.requestHandler|`requestHandler`}.
* See {@apilink Router.addHandler|`router.addHandler()`} and {@apilink Router.addDefaultHandler|`router.addDefaultHandler()`}.
*/
readonly router: RouterHandler<Context> = Router.create<Context>();
private _basicContextPipeline?: ContextPipeline<{ request: Request }, CrawlingContext>;
/**
* The basic part of the context pipeline. Unlike the subclass pipeline, this
* part has no major side effects (e.g. launching a browser). It also makes typing more explicit, as subclass
* pipelines expect the basic crawler fields to already be present in the context at runtime.
*
* Context built with this pipeline can be passed into multiple crawler pipelines at once.
* This is used e.g. in the {@apilink AdaptivePlaywrightCrawler|`AdaptivePlaywrightCrawler`}.
*/
get basicContextPipeline(): ContextPipeline<{ request: Request }, CrawlingContext> {
if (this._basicContextPipeline === undefined) {
this._basicContextPipeline = this.buildBasicContextPipeline();
}
return this._basicContextPipeline;
}
private _contextPipeline?: ContextPipeline<CrawlingContext, ExtendedContext>;
get contextPipeline(): ContextPipeline<CrawlingContext, ExtendedContext> {
if (this._contextPipeline === undefined) {
this._contextPipeline = this.buildFinalContextPipeline();
}
return this._contextPipeline;
}
running = false;
hasFinishedBefore = false;
protected unexpectedStop = false;
#log!: CrawleeLogger;
get log(): CrawleeLogger {
return this.#log;
}
protected requestHandler!: RequestHandler<ExtendedContext>;
protected errorHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;
protected failedRequestHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;
protected requestHandlerTimeoutMillis!: number;
protected internalTimeoutMillis: number;
protected maxRequestRetries: number;
protected maxCrawlDepth?: number;
protected sameDomainDelayMillis: number;
protected domainAccessedTime: Map<string, number>;
protected maxRequestsPerCrawl?: number;
protected handledRequestsCount = 0;
protected statusMessageLoggingInterval: number;
protected statusMessageCallback?: StatusMessageCallback;
protected blockedStatusCodes = new Set<number>();
protected additionalHttpErrorStatusCodes: Set<number>;
protected ignoreHttpErrorStatusCodes: Set<number>;
protected autoscaledPoolOptions: AutoscaledPoolOptions;
protected httpClient: BaseHttpClient;
protected retryOnBlocked: boolean;
protected respectRobotsTxtFile: boolean | { userAgent?: string };
protected onSkippedRequest?: SkippedRequestCallback;
private _closeEvents?: boolean;
private loggedPerRun = new Set<string>();
private experiments: CrawlerExperiments;
private readonly robotsTxtFileCache: LruCache<RobotsTxtFile>;
private _experimentWarnings: Partial<Record<keyof CrawlerExperiments, boolean>> = {};
private readonly crawlerId: string;
private readonly hasExplicitId: boolean;
private readonly contextPipelineOptions: {
contextPipelineBuilder?: () => ContextPipeline<CrawlingContext, Context>;
extendContext?: (context: Context) => Awaitable<ContextExtension>;
};
protected static optionsShape = {
contextPipelineBuilder: ow.optional.object,
extendContext: ow.optional.function,
requestList: ow.optional.object.validate(validators.requestList),
requestQueue: ow.optional.object.validate(validators.requestQueue),
// Subclasses override this function instead of passing it
// in constructor, so this validation needs to apply only
// if the user creates an instance of BasicCrawler directly.
requestHandler: ow.optional.function,
requestHandlerTimeoutSecs: ow.optional.number,
errorHandler: ow.optional.function,
failedRequestHandler: ow.optional.function,
maxRequestRetries: ow.optional.number,
sameDomainDelaySecs: ow.optional.number,
maxRequestsPerCrawl: ow.optional.number,
maxCrawlDepth: ow.optional.number,
autoscaledPoolOptions: ow.optional.object,
sessionPool: ow.optional.object.validate(validators.sessionPool),
proxyConfiguration: ow.optional.object.validate(validators.proxyConfiguration),
statusMessageLoggingInterval: ow.optional.number,
statusMessageCallback: ow.optional.function,
additionalHttpErrorStatusCodes: ow.optional.array.ofType(ow.number),
ignoreHttpErrorStatusCodes: ow.optional.array.ofType(ow.number),
blockedStatusCodes: ow.optional.array.ofType(ow.number),
retryOnBlocked: ow.optional.boolean,
respectRobotsTxtFile: ow.optional.any(ow.boolean, ow.object),
onSkippedRequest: ow.optional.function,
httpClient: ow.optional.object,
configuration: ow.optional.object,
storageClient: ow.optional.object,
eventManager: ow.optional.object,
logger: ow.optional.object,
// AutoscaledPool shorthands
minConcurrency: ow.optional.number,
maxConcurrency: ow.optional.number,
maxRequestsPerMinute: ow.optional.number.integerOrInfinite.positive.greaterThanOrEqual(1),
keepAlive: ow.optional.boolean,
// internal
experiments: ow.optional.object,
statisticsOptions: ow.optional.object,
id: ow.optional.string,
};
/**
* All `BasicCrawler` parameters are passed via an options object.
*/
constructor(
options: BasicCrawlerOptions<Context, ContextExtension, ExtendedContext> &
RequireContextPipeline<CrawlingContext, Context> = {} as any, // cast because the constructor logic handles missing `contextPipelineBuilder` - the type is just for DX
) {
ow(options, 'BasicCrawlerOptions', ow.object.exactShape(BasicCrawler.optionsShape));
const {
requestList,
requestQueue,
requestManager,
maxRequestRetries = 3,
sameDomainDelaySecs = 0,
maxRequestsPerCrawl,
maxCrawlDepth,
autoscaledPoolOptions = {},
keepAlive,
sessionPool,
proxyConfiguration,
additionalHttpErrorStatusCodes = [],
ignoreHttpErrorStatusCodes = [],
// Service locator options
configuration,
storageClient,
eventManager,
logger,
// AutoscaledPool shorthands
minConcurrency,
maxConcurrency,
maxRequestsPerMinute,
blockedStatusCodes: blockedStatusCodesInput,
retryOnBlocked = false,
respectRobotsTxtFile = false,
onSkippedRequest,
requestHandler,
requestHandlerTimeoutSecs,
errorHandler,
failedRequestHandler,
statusMessageLoggingInterval = 10,
statusMessageCallback,
statisticsOptions,
httpClient,
// internal
experiments = {},
id,
} = options;
// Create per-crawler service locator if custom services were provided.
// This wraps every method on the crawler instance so that calls to the global `serviceLocator`
// (via AsyncLocalStorage) resolve to this scoped instance instead.
// We also enter the scope for the rest of the constructor body, so that any code below
// that accesses `serviceLocator` will see the correct (scoped) instance.
let serviceLocatorScope = { enterScope: () => {}, exitScope: () => {} };
if (
storageClient ||
eventManager ||
logger ||
(configuration !== undefined && configuration !== serviceLocator.getConfiguration())
) {
const scopedServiceLocator = new ServiceLocator(configuration, eventManager, storageClient, logger);
serviceLocatorScope = bindMethodsToServiceLocator(scopedServiceLocator, this);
}
try {
serviceLocatorScope.enterScope();
this.contextPipelineOptions = {
contextPipelineBuilder: options.contextPipelineBuilder,
extendContext: options.extendContext,
};
this.#log = serviceLocator.getLogger().child({ prefix: this.constructor.name });
// Store whether the user explicitly provided an ID
this.hasExplicitId = id !== undefined;
// Store the user-provided ID, or generate a unique one for tracking purposes (not for state key)
this.crawlerId = id ?? cryptoRandomObjectId();
if (requestManager !== undefined) {
if (requestList !== undefined || requestQueue !== undefined) {
throw new Error(
'The `requestManager` option cannot be used in conjunction with `requestList` and/or `requestQueue`',
);
}
this.requestManager = requestManager;
this.requestQueue = requestManager as RequestProvider; // TODO(v4) - the cast is not fully legitimate here, but it's fine for internal usage by the BasicCrawler
} else {
this.requestList = requestList;
this.requestQueue = requestQueue;
}
this.httpClient = httpClient ?? new GotScrapingHttpClient({ logger: this.log });
this.proxyConfiguration = proxyConfiguration;
this.statusMessageLoggingInterval = statusMessageLoggingInterval;
this.statusMessageCallback = statusMessageCallback as StatusMessageCallback;
this.domainAccessedTime = new Map();
this.experiments = experiments;
this.robotsTxtFileCache = new LruCache({ maxLength: 1000 });
this.handleSkippedRequest = this.handleSkippedRequest.bind(this);
this.additionalHttpErrorStatusCodes = new Set([...additionalHttpErrorStatusCodes]);
this.ignoreHttpErrorStatusCodes = new Set([...ignoreHttpErrorStatusCodes]);
this.requestHandler = requestHandler ?? this.router;
this.failedRequestHandler = failedRequestHandler;
this.errorHandler = errorHandler;
if (requestHandlerTimeoutSecs) {
this.requestHandlerTimeoutMillis = requestHandlerTimeoutSecs * 1000;
} else {
this.requestHandlerTimeoutMillis = 60_000;
}
this.retryOnBlocked = retryOnBlocked;
this.respectRobotsTxtFile = respectRobotsTxtFile;
this.onSkippedRequest = onSkippedRequest;
const tryEnv = (val?: string) => (val == null ? null : +val);
// allow at least 5min for internal timeouts
this.internalTimeoutMillis =
tryEnv(process.env.CRAWLEE_INTERNAL_TIMEOUT) ?? Math.max(this.requestHandlerTimeoutMillis * 2, 300e3);
// override the default internal timeout of request queue to respect `requestHandlerTimeoutMillis`
if (this.requestQueue) {
this.requestQueue.internalTimeoutMillis = this.internalTimeoutMillis;
// for request queue v2, we want to lock requests for slightly longer than the request handler timeout so that there is some padding for locking-related overhead,
// but never for less than a minute
this.requestQueue.requestLockSecs = Math.max(this.requestHandlerTimeoutMillis / 1000 + 5, 60);
}
this.maxRequestRetries = maxRequestRetries;
this.maxCrawlDepth = maxCrawlDepth;
this.sameDomainDelayMillis = sameDomainDelaySecs * 1000;
this.stats = new Statistics({
logMessage: `${this.constructor.name} request statistics:`,
log: this.log,
...(this.hasExplicitId ? { id: this.crawlerId } : {}),
...statisticsOptions,
});
if (sessionPool && proxyConfiguration) {
this.log.warning(
'Both `sessionPool` and `proxyConfiguration` were provided to the crawler. ' +
'The `proxyConfiguration` is ignored - sessions from the supplied pool keep whatever ' +
'`proxyInfo` they were created with. Configure proxies on the pool instead, ' +
'e.g. via `addSession({ proxyInfo })` or a custom `createSessionFunction`.',
);
}
if (sessionPool) {
this.sessionPool = sessionPool;
} else {
this.ownedSessionPool = new SessionPool({
createSessionFunction: async (opts) =>
new Session({
...opts?.sessionOptions,
proxyInfo:
opts?.sessionOptions?.proxyInfo ?? (await this.proxyConfiguration?.newProxyInfo()),
}),
});
this.sessionPool = this.ownedSessionPool;
}
this.blockedStatusCodes = new Set(blockedStatusCodesInput ?? BLOCKED_STATUS_CODES);
const maxSignedInteger = 2 ** 31 - 1;
if (this.requestHandlerTimeoutMillis > maxSignedInteger) {
this.log.warning(
`requestHandlerTimeoutMillis ${this.requestHandlerTimeoutMillis}` +
` does not fit a signed 32-bit integer. Limiting the value to ${maxSignedInteger}`,
);
this.requestHandlerTimeoutMillis = maxSignedInteger;
}
this.internalTimeoutMillis = Math.min(this.internalTimeoutMillis, maxSignedInteger);
this.maxRequestsPerCrawl = maxRequestsPerCrawl;
const isMaxPagesExceeded = () =>
this.maxRequestsPerCrawl && this.maxRequestsPerCrawl <= this.handledRequestsCount;
// eslint-disable-next-line prefer-const
let { isFinishedFunction, isTaskReadyFunction } = autoscaledPoolOptions;
// override even if `isFinishedFunction` provided by user - `keepAlive` has higher priority
if (keepAlive) {
isFinishedFunction = async () => false;
}
const basicCrawlerAutoscaledPoolConfiguration: Partial<AutoscaledPoolOptions> = {
minConcurrency: minConcurrency ?? autoscaledPoolOptions?.minConcurrency,
maxConcurrency: maxConcurrency ?? autoscaledPoolOptions?.maxConcurrency,
maxTasksPerMinute: maxRequestsPerMinute ?? autoscaledPoolOptions?.maxTasksPerMinute,
runTaskFunction: async () => {
const source = this.requestManager;
if (!source) throw new Error('Request provider is not initialized!');
const request = await this.resolveRequest();
if (!request || this.delayRequest(request, source)) {
return;
}
const crawlingContext = { request } as { request: Request } & Partial<CrawlingContext>;
try {
await this.basicContextPipeline
.chain(this.contextPipeline)
.call(crawlingContext, (ctx) => this.handleRequest(ctx, source, request));
} catch (error) {
// ContextPipelineInterruptedError means the request was intentionally skipped
// (e.g., doesn't match enqueue strategy after redirect). Just return gracefully.
if (error instanceof ContextPipelineInterruptedError) {
await this._timeoutAndRetry(
async () => this.requestManager?.markRequestHandled(request),
this.internalTimeoutMillis,
`Marking request ${crawlingContext.request.url} (${crawlingContext.request.id}) as handled timed out after ${
this.internalTimeoutMillis / 1e3
} seconds.`,
);
return;
}
// If the error happened during pipeline initialization (e.g., navigation timeout, session/proxy error,
// i.e. not in user's requestHandler), handle it through the normal error flow.
const isPipelineError =
error instanceof ContextPipelineInitializationError || error instanceof SessionError;
if (isPipelineError) {
const unwrappedError = this.unwrapError(error);
await this._requestFunctionErrorHandler(
unwrappedError,
crawlingContext as CrawlingContext,
request,
this.requestManager!,
);
// SessionError already retired the session in `_requestFunctionErrorHandler`;
// skip `markBad` to avoid double-counting usage/error score.
if (!(unwrappedError instanceof SessionError)) {
crawlingContext.session?.markBad();
}
return;
}
throw this.unwrapError(error);
}
},
isTaskReadyFunction: async () => {
if (isMaxPagesExceeded()) {
this.logOncePerRun(
'shuttingDown',
'Crawler reached the maxRequestsPerCrawl limit of ' +
`${this.maxRequestsPerCrawl} requests and will shut down soon. Requests that are in progress will be allowed to finish.`,
);
return false;
}
if (this.unexpectedStop) {
this.logOncePerRun(
'shuttingDown',
'No new requests are allowed because the `stop()` method has been called. ' +
'Ongoing requests will be allowed to complete.',
);
return false;
}
return isTaskReadyFunction ? await isTaskReadyFunction() : await this._isTaskReadyFunction();
},
isFinishedFunction: async () => {
if (isMaxPagesExceeded()) {
this.log.info(
`Earlier, the crawler reached the maxRequestsPerCrawl limit of ${this.maxRequestsPerCrawl} requests ` +
'and all requests that were in progress at that time have now finished. ' +
`In total, the crawler processed ${this.handledRequestsCount} requests and will shut down.`,