-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathbasic-crawler.ts
More file actions
3028 lines (2634 loc) · 136 KB
/
Copy pathbasic-crawler.ts
File metadata and controls
3028 lines (2634 loc) · 136 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 { mkdir, writeFile } from 'node:fs/promises';
import { dirname } from 'node:path';
import type {
AddRequestsBatchedOptions,
AddRequestsBatchedResult,
AutoscaledPoolOptions,
ConcurrencySystemOptions,
CrawleeLogger,
CrawlingContext,
DatasetExportOptions,
EnqueueUrlsOptions,
EventStatusMessageData,
FinalStatistics,
GetUserDataFromRequest,
IConcurrencySystem,
IProxyConfiguration,
IRequestLoader,
IRequestManager,
IStatistics,
RequestsLike,
RouterHandler,
RouterRoutes,
SkippedRequestCallback,
SkippedRequestReason,
Source,
StatisticState,
StorageIdentifier,
StorageWritePolicy,
TaskLoopPredicates,
TypedRequestsLike,
UrlPatternObject,
} from '@crawlee/core';
import {
applyRequestTransform,
AutoscaledPool,
bindMethodsToServiceLocator,
BLOCKED_STATUS_CODES,
buildEnqueueStrategyPatterns,
ConcurrencySystem,
Configuration,
constructUrlPatternObjects,
ContextPipeline,
ContextPipelineCleanupError,
ContextPipelineInitializationError,
ContextPipelineInterruptedError,
createRequestOptions,
createStorageTransaction,
Request,
CriticalError,
currentStorageTransaction,
Dataset,
EnqueueStrategy,
EventManager,
EventType,
filterRequestOptionsByPatterns,
getObjectType,
KeyValueStore,
log,
LogLevel,
mergeCookies,
MissingSessionError,
NavigationSkippedError,
NonRetryableError,
OwnedOrInjected,
purgeDefaultStorages,
RequestHandlerError,
parseRetryAfterHeader,
RequestThrottledError,
RequestManagerTandem,
RequestQueue,
RequestState,
RetryRequestError,
supportsDomainThrottling,
Router,
ServiceLocator,
serviceLocator,
Session,
SessionError,
SessionPool,
Statistics,
ThrottlingRequestManager,
validateUserData,
validators,
withDirectStorageAccess,
} from '@crawlee/core';
import { BaseHttpClient, FetchHttpClient } from '@crawlee/http-client';
import type {
Awaitable,
Dictionary,
ISession,
ISessionPool,
ProxyInfo,
SetStatusMessageOptions,
StorageBackend,
} from '@crawlee/types';
import { isAsyncIterable, isIterable, parseArgument, ROTATE_PROXY_ERRORS, schemas } from '@crawlee/utils/internal';
import { RobotsTxtFile } from '@crawlee/utils';
import { getDomain } from 'tldts';
import type { ReadonlyDeep } from 'type-fest';
import { z } from 'zod';
import { LruCache } from '@apify/datastructures';
import { addTimeoutToPromise, extendTimeout, TimeoutError } from '@apify/timeout';
import { cryptoRandomObjectId } from '@apify/utilities';
import {
extendTimeoutKey,
navigationDeadlineKey,
raceWithTimeout,
type RequestTimeoutContext,
timeoutExpiredKey,
} from './request-timeout.js';
import { createSendRequest } from './send-request.js';
class LazyDefaultHttpClient extends BaseHttpClient {
readonly #delegatePromise: Promise<BaseHttpClient>;
constructor(options?: { logger?: CrawleeLogger }) {
super(options);
this.#delegatePromise = import('@crawlee/impit-client')
.then(({ ImpitHttpClient }) => new ImpitHttpClient(options))
.catch(() => {
(options?.logger ?? log).warning(
'Optional dependency @crawlee/impit-client is not installed. ' +
'Falling back to native fetch — proxy support and browser fingerprinting are unavailable.',
);
return new FetchHttpClient(options);
});
}
protected fetch(): Promise<Response> {
throw new Error('LazyDefaultHttpClient delegates `sendRequest` entirely; `fetch` is never called.');
}
override async sendRequest(...args: Parameters<BaseHttpClient['sendRequest']>): Promise<Response> {
return (await this.#delegatePromise).sendRequest(...args);
}
}
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');
// The request timeout plumbing (the window helper, the context symbols, and the race) lives in its own module.
export { navigationDeadlineKey, remainingNavigationWindowMillis } from './request-timeout.js';
const urlPatternSchema = z.union([
z.string(),
z.instanceof(RegExp),
schemas.objectWithKeys(['glob']),
schemas.objectWithKeys(['regexp']),
]);
// `looseObject` (rather than `strictObject`) lets subclasses forward their own extraction-only options
// (e.g. `selector`) straight through without having to strip them out first.
const addRequestsOptionsSchema = z.looseObject({
forefront: z.boolean().optional(),
cache: z.boolean().optional(),
waitForAllRequestsToBeAdded: z.boolean().optional(),
batchSize: schemas.anyNumber.optional(),
waitBetweenBatchesMillis: schemas.anyNumber.optional(),
maxNewRequests: schemas.anyNumber.optional(),
limit: schemas.anyNumber.optional(),
baseUrl: z.string().optional(),
userData: schemas.anyObject.optional(),
label: z.string().optional(),
sessionId: z.string().optional(),
skipNavigation: z.boolean().optional(),
include: schemas.arrayOf(urlPatternSchema, 'URL patterns').min(1).optional(),
exclude: schemas.arrayOf(urlPatternSchema, 'URL patterns').optional(),
transformRequestFunction: schemas.anyFunction.optional(),
strategy: z.enum(EnqueueStrategy).optional(),
onSkippedRequest: schemas.anyFunction.optional(),
});
/** The in-flight context, carrying the timeout slots ({@apilink raceWithTimeout} hangs its extender on them). */
type PendingCrawlingContext = { request: Request } & Partial<CrawlingContext> & RequestTimeoutContext;
export type RequestHandler<Context extends CrawlingContext = CrawlingContext> = (inputs: Context) => Awaitable<void>;
/**
* An error handler receives the crawling context and the error that was thrown while processing the request.
*
* Unlike the {@apilink RequestHandler}, an error handler may run before the context pipeline has finished
* building the full context (e.g. when navigation or session setup fails). Therefore only `BaseContext` is
* guaranteed to be present, while the extra properties added by the pipeline and `extendContext` (the
* difference between `BaseContext` and `ExtendedContext`) are only available as a `Partial`.
*/
export type ErrorHandler<
BaseContext extends CrawlingContext = CrawlingContext,
ExtendedContext extends BaseContext = BaseContext,
> = (inputs: BaseContext & Partial<ExtendedContext>, error: Error) => Awaitable<void>;
export interface StatusMessageCallbackParams<
Context extends CrawlingContext = BasicCrawlingContext,
Crawler extends BasicCrawler<any, any, any, any> = BasicCrawler<Context>,
> {
state: StatisticState;
crawler: Crawler;
previousState: StatisticState;
message: string;
}
export type StatusMessageCallback<
Context extends CrawlingContext = BasicCrawlingContext,
Crawler extends BasicCrawler<any, any, any, 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,
Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<Context['request']>>,
StatisticStateExtension extends object = {},
> {
/**
* 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?: RouterHandler<ExtendedContext, Routes> | RequestHandler<ExtendedContext>;
/**
* Allows the user to extend the crawling context with custom functionality (helpers, references, etc.).
*
* `extendContext` runs *before* navigation, so the returned members are visible to the
* `preNavigationHooks`, `postNavigationHooks`, and the `requestHandler` alike. As a consequence,
* the `context` passed to `extendContext` is the pre-navigation {@apilink CrawlingContext} and does
* **not** include navigation-dependent members (e.g. `page`, `response`, `$`, `body`). If you need
* those, use a `postNavigationHook` or the `requestHandler` instead.
*
* **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: CrawlingContext) => 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.
*
* @deprecated Use the `requestManager` option instead. To combine a read-only loader (such as a `RequestList`)
* with a writable queue, build a tandem with {@apilink IRequestLoader.toTandem|`requestList.toTandem(requestQueue)`}
* and pass the result as `requestManager`. When both `requestList` and `requestQueue` are provided, they are
* combined into a tandem automatically.
*/
requestList?: IRequestLoader;
/**
* Dynamic queue of URLs to be processed. This is useful for recursive crawling of websites.
*
* @deprecated Use the `requestManager` option instead. A `RequestQueue` is itself a request manager, so you can
* pass it directly as `requestManager`.
*/
requestQueue?: RequestQueue;
/**
* Manager of requests that should be processed by the crawler. Mutually exclusive with the deprecated
* `requestQueue` and `requestList` options.
*
* If not provided, the crawler will open the default {@apilink RequestQueue} when it is first needed.
*/
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. Subdomains are
* paced together with the site they belong to.
*
* Wraps the crawler's request manager in a {@apilink ThrottlingRequestManager}; pass one as `requestManager`
* yourself to configure it further.
* @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;
/**
* Lets you override the predicates that steer the crawler's task loop: `isTaskReadyFunction` (may another request
* start?) and `isFinishedFunction` (is the crawl over?). The task itself — fetching a request and running it
* through the pipeline — is owned by the crawler and cannot be overridden.
*
* Concurrency is configured elsewhere — through the `minConcurrency`/`maxConcurrency`/`maxRequestsPerMinute`
* shortcuts, or a {@apilink BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} for finer control.
*/
taskLoopOptions?: TaskLoopPredicates;
/**
* A pre-configured concurrency governor — the component that decides whether there is free compute for one more
* task. Typically a {@apilink ConcurrencySystem}, though any {@apilink IConcurrencySystem} is accepted. All
* scaling configuration (min/max/desired concurrency, scaling ratios, `maxTasksPerMinute`, snapshotter tuning)
* lives on the instance itself.
*
* Inject the *same* instance into several concurrent crawlers to cap their **combined** concurrency against a
* single budget. Each crawler still builds and drives its own {@apilink AutoscaledPool}; only the load/scaling
* accounting is shared.
*
* Mutually exclusive with the `minConcurrency`/`maxConcurrency`/`maxRequestsPerMinute` shortcuts, which configure
* the default system this one replaces — combining the two throws.
*
* You own a supplied system's lifecycle: `start()` it before `run()` (which throws otherwise) and `stop()` it once
* every crawler borrowing it has finished. The crawler does neither on your behalf.
*/
concurrencySystem?: IConcurrencySystem;
/**
* Sets the minimum concurrency (parallelism) for the crawl. Shortcut for the
* {@apilink ConcurrencySystemOptions.minConcurrency|`minConcurrency`} option of the crawler's default
* {@apilink ConcurrencySystem}.
* > *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
* {@apilink ConcurrencySystemOptions.maxConcurrency|`maxConcurrency`} option of the crawler's default
* {@apilink ConcurrencySystem}.
*/
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 {@apilink ConcurrencySystemOptions.maxTasksPerMinute|`maxTasksPerMinute`} option of the
* crawler's default {@apilink ConcurrencySystem}.
*/
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.
*
* A 429 from a domain covered by a {@apilink ThrottlingRequestManager} is handled as a rate limit before
* this is consulted, so removing 429 here only affects domains that manager does not cover.
*
* @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;
/**
* A preconfigured statistics instance. When provided, the crawler records into it instead of building its own and
* will not `reset()` it between `run()` calls. Accepts the built-in {@apilink Statistics} or any object
* implementing {@apilink IStatistics}.
*
* Custom fields declared via {@apilink StatisticsOptions.stateExtension|`stateExtension`} are carried over to
* {@apilink BasicCrawler.statistics|`crawler.statistics.state`}:
*
* ```ts
* const statistics = new Statistics({ stateExtension: { defaultState: { productsFound: 0 } } });
*
* const crawler = new BasicCrawler({
* statistics,
* requestHandler: async () => {
* statistics.state.productsFound++;
* },
* });
*
* await crawler.run();
* // the custom fields are typed on `crawler.statistics` too
* console.log(crawler.statistics.state.productsFound);
* ```
*/
statistics?: IStatistics<StatisticStateExtension>;
/**
* HTTP client implementation for the `sendRequest` context helper and for plain HTTP crawling.
* Defaults to {@apilink ImpitHttpClient} when `@crawlee/impit-client` is installed, otherwise {@apilink FetchHttpClient}.
*/
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?: IProxyConfiguration;
/**
* 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 backend to use for this crawler.
* If provided, the crawler will use its own ServiceLocator instance instead of the global one.
*/
storageBackend?: StorageBackend;
/**
* 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;
/**
* Makes the storage writes performed while handling a request atomic with respect to the request
* succeeding: they are recorded in a {@apilink StorageTransaction} spanning the whole request
* lifecycle and only applied when the request handler succeeds, so a thrown handler leaves no partial
* writes behind and a retry does not double-write. Reads within the handler see its own writes.
*
* `false` disables the mechanism entirely; an object overrides the per-storage-type
* {@apilink StorageWritePolicy} (e.g. `{ requestQueue: 'deferred' }` for all-or-nothing enqueues).
* {@apilink withDirectStorageAccess} is the per-call-site escape hatch; `useState()` is deliberately
* *not* transactional.
*
* @default true
*/
transactionalStorage?: boolean | Partial<StorageWritePolicy>;
/**
* 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[];
}
/**
* 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 IRequestManager|request manager} provided via the
* {@apilink BasicCrawlerOptions.requestManager|`requestManager`} constructor option (a {@apilink RequestQueue} is
* itself a request manager). If no `requestManager` is provided, the crawler opens the default {@apilink RequestQueue}
* either when the {@apilink BasicCrawler.addRequests|`crawler.addRequests()`} function is called, or if the `requests`
* parameter (representing the initial requests) of the {@apilink BasicCrawler.run|`crawler.run()`} function is provided.
*
* To read requests from a read-only source such as a {@apilink RequestList} or {@apilink SitemapRequestLoader} while
* still being able to enqueue new ones, combine the loader with a queue into a {@apilink RequestManagerTandem} using
* {@apilink IRequestLoader.toTandem|`requestLoader.toTandem()`} and pass the result as `requestManager`. The tandem
* first processes URLs from the loader and automatically enqueues them into the queue, ensuring a single URL is not
* crawled multiple times.
*
* > The legacy {@apilink BasicCrawlerOptions.requestList|`requestList`} and
* > {@apilink BasicCrawlerOptions.requestQueue|`requestQueue`} options are deprecated. They are still accepted and
* > folded into a single `requestManager` (combined into a tandem when both are given), but new code should use
* > `requestManager` directly.
*
* 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, as judged by the crawler's
* {@apilink ConcurrencySystem}.
* Concurrency is tuned via the {@apilink BasicCrawlerOptions.minConcurrency|`minConcurrency`},
* {@apilink BasicCrawlerOptions.maxConcurrency|`maxConcurrency`} and
* {@apilink BasicCrawlerOptions.maxRequestsPerMinute|`maxRequestsPerMinute`} shortcuts, or, for finer control, by
* injecting a pre-configured {@apilink BasicCrawlerOptions.concurrencySystem|`concurrencySystem`}.
*
* **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
*/
/**
* Identifies a crawler instance for storage aliasing, `useState()` and status-message events.
*/
interface CrawlerIdentity {
/**
* 0-based instantiation order across all crawlers in the process.
* Note that the value can be subject to race conditions between different script invocations.
*/
readonly instanceIndex: number;
/** The user-supplied `id` option, or a fallback derived from `instanceIndex`. */
readonly id: string;
/** Whether `id` came from the user (as opposed to being derived from `instanceIndex`). */
readonly hasExplicitId: boolean;
}
export class BasicCrawler<
Context extends CrawlingContext = CrawlingContext,
ContextExtension = Dictionary<never>,
ExtendedContext extends Context = Context & ContextExtension,
Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<Context['request']>>,
StatisticStateExtension extends object = {},
> {
static readonly #CRAWLEE_STATE_KEY = 'CRAWLEE_STATE';
/**
* Tracks the number of crawler instances created. The first crawler uses the default
* request queue; subsequent ones get their own queue via a unique alias so they don't
* collide.
*/
// kept as TS-private: tests reset the counter at runtime
private static instanceCount = 0;
/**
* Tracks crawler instances that accessed shared state without having an explicit id.
* Used to detect and warn about multiple crawlers sharing the same state.
*/
static #useStateAnonymousIndices = new Set<number>();
/** Backs the {@apilink BasicCrawler.statistics|`statistics`} getter. */
#statisticsDep: OwnedOrInjected<IStatistics<StatisticStateExtension>, Statistics<StatisticStateExtension>>;
/**
* The statistics instance collecting the crawler's run statistics - either the injected `statistics` option or a
* crawler-built default. Typed as {@apilink IStatistics} so custom implementations can be plugged in.
*/
get statistics(): IStatistics<StatisticStateExtension> {
return this.#statisticsDep.value;
}
/**
* The main request-handling component of the crawler. It manages the requests that the crawler processes,
* combining any provided request loader and/or queue. It's initialized during the crawler startup or lazily
* via {@apilink BasicCrawler.getRequestManager|`getRequestManager()`}.
*/
protected requestManager?: IRequestManager;
/** Backs the {@apilink BasicCrawler.sessionPool|`sessionPool`} getter. */
#sessionPoolDep: OwnedOrInjected<ISessionPool, SessionPool>;
/**
* 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.
*/
get sessionPool(): ISessionPool {
return this.#sessionPoolDep.value;
}
/**
* Tracks **only** the queue the crawler opens for itself — not the {@apilink RequestManagerTandem} that may wrap it
* around a user-supplied `requestList` — so the owned-only purge between repeated `run()` calls never reaches
* through to a borrowed loader. Filled lazily in {@apilink BasicCrawler.openOwnedRequestQueue|`openOwnedRequestQueue()`}.
*/
#ownedRequestQueue = OwnedOrInjected.resolve<RequestQueue>();
/**
* Whether the request-processing-time hint has already been forwarded to the request manager. The hint
* derives only from `requestHandlerTimeoutMillis` (constant for the crawler's lifetime) and is raise-only,
* so it only needs to be applied once, at the first async access of the manager.
*/
#requestManagerTimeoutsApplied = false;
/**
* Resolves the governor for one run: either the injected
* {@apilink BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} (borrowed) or a freshly built default with
* the concurrency shortcuts folded in (owned, so the crawler starts and stops it).
*/
readonly #resolveConcurrencySystem: () => OwnedOrInjected<IConcurrencySystem, ConcurrencySystem>;
/** As resolved by `init()`. Absent until the first run, so a `teardown()` before it is a no-op. */
#concurrencySystemDep?: OwnedOrInjected<IConcurrencySystem, ConcurrencySystem>;
/**
* The concurrency governor this run is booking its requests against — either the
* {@apilink BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} that was injected, or the default the
* crawler built for itself. Read it for telemetry: `desiredConcurrency`, `currentConcurrency`, `isRunning`.
*
* > *NOTE:* `undefined` until {@apilink BasicCrawler.run|`crawler.run()`} has resolved it. A crawler-owned default
* is also rebuilt for every run, so the instance is not stable across runs.
*
* {@apilink IConcurrencySystem} is deliberately read-only. Tuning concurrency *while a crawl is running* means
* owning the instance: build a {@apilink ConcurrencySystem} yourself and inject it, then set
* `minConcurrency`/`maxConcurrency`/`desiredConcurrency` on your own reference.
*/
get concurrencySystem(): IConcurrencySystem | undefined {
return this.#concurrencySystemDep?.maybeValue;
}
/**
* The task loop that dispatches this run's requests. Private on purpose — it is a bare parallel task runner with
* no configuration left of its own (see {@apilink ConcurrencySystem}), and everything a caller legitimately did
* with it now has a crawler-level counterpart: {@apilink BasicCrawler.pause|`pause()`},
* {@apilink BasicCrawler.resume|`resume()`}, {@apilink BasicCrawler.teardown|`teardown()`} and
* {@apilink BasicCrawler.concurrencySystem|`concurrencySystem`}.
*/
#autoscaledPool?: AutoscaledPool;
/**
* A reference to the underlying {@apilink IProxyConfiguration} instance that manages the crawler's proxies.
* Only available if used by the crawler.
*/
readonly proxyConfiguration?: IProxyConfiguration;
/**
* 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, Routes> = Router.create<Context>() as unknown as RouterHandler<
Context,
Routes
>;
#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;
}
#contextPipeline?: ContextPipeline<CrawlingContext, ExtendedContext>;
get contextPipeline(): ContextPipeline<CrawlingContext, ExtendedContext> {
if (this.#contextPipeline === undefined) {
this.#contextPipeline = this.buildFinalContextPipeline();
}
return this.#contextPipeline;
}
running = false;
hasFinishedBefore = false;
#unexpectedStop = false;
#log!: CrawleeLogger;
get log(): CrawleeLogger {
return this.#log;
}
protected readonly requestHandler!: RequestHandler<ExtendedContext>;
readonly #errorHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;
readonly #failedRequestHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;
// kept as TS-private: tests read it at runtime
private requestHandlerTimeoutMillis!: number;
protected readonly internalTimeoutMillis: number;
readonly #maxRequestRetries: number;
readonly #maxCrawlDepth?: number;
#sameDomainDelaySecs: number;
readonly #maxRequestsPerCrawl?: number;
private get handledRequestsCount(): number {
return this.statistics.state.requestsFinished + this.statistics.state.requestsFailed;
}
#statusMessageLoggingInterval: number;
#statusMessageCallback?: StatusMessageCallback;
protected blockedStatusCodes = new Set<number>();
protected readonly additionalHttpErrorStatusCodes: Set<number>;
#ignoreHttpErrorStatusCodes: Set<number>;
/**
* The resolved options for the crawler's own task loop — the crawler-owned `runTaskFunction`, the (possibly
* user-overridden) ready/finished predicates and cadence/logging. Concurrency configuration lives on the
* {@apilink ConcurrencySystem} instead, and the loop's `consumer` identity is the crawler's own, so neither is
* settable here.
*/
// kept as TS-private: tests mutate it at runtime
private taskLoopOptions: Omit<AutoscaledPoolOptions, 'concurrencySystem' | 'consumer'>;
protected readonly httpClient: BaseHttpClient;
protected readonly retryOnBlocked: boolean;
#respectRobotsTxtFile: boolean | { userAgent?: string };
/** Whether `runInStorageTransaction()` opens a transaction at all. */
readonly #transactionalStorageEnabled: boolean;
/** The resolved per-storage-type write policy overrides forwarded to each request's transaction. */
readonly #storageWritePolicy: Partial<StorageWritePolicy>;
readonly #onSkippedRequest?: SkippedRequestCallback;
#closeEvents?: boolean;
#loggedPerRun = new Set<string>();
readonly #robotsTxtFileCache: LruCache<RobotsTxtFile>;
readonly #identity: CrawlerIdentity;
readonly #contextPipelineOptions: {
contextPipelineBuilder?: () => ContextPipeline<CrawlingContext, Context>;
extendContext?: (context: CrawlingContext) => Awaitable<ContextExtension>;
};
/**
* @internal
*/
protected static optionsShape = {
contextPipelineBuilder: schemas.anyObject.optional(),
extendContext: schemas.anyFunction.optional(),
requestList: validators.requestList.optional(),
requestQueue: validators.requestQueue.optional(),
requestManager: validators.requestManager.optional(),
// 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: schemas.anyFunction.optional(),
requestHandlerTimeoutSecs: schemas.anyNumber.optional(),
errorHandler: schemas.anyFunction.optional(),
failedRequestHandler: schemas.anyFunction.optional(),
maxRequestRetries: schemas.anyNumber.default(3),
sameDomainDelaySecs: schemas.anyNumber.default(0),
maxRequestsPerCrawl: schemas.anyNumber.optional(),
maxCrawlDepth: schemas.anyNumber.optional(),
// No zod default — subclasses provide their own fallback (e.g. HTTP-optimized pool options).
taskLoopOptions: schemas.anyObject.optional(),
concurrencySystem: schemas.anyObject.optional(),
sessionPool: validators.sessionPool.optional(),
proxyConfiguration: validators.proxyConfiguration.optional(),
statusMessageLoggingInterval: schemas.anyNumber.default(10),
statusMessageCallback: schemas.anyFunction.optional(),
additionalHttpErrorStatusCodes: schemas.arrayOf(schemas.anyNumber, 'numbers').default(() => []),
ignoreHttpErrorStatusCodes: schemas.arrayOf(schemas.anyNumber, 'numbers').default(() => []),
blockedStatusCodes: schemas.arrayOf(schemas.anyNumber, 'numbers').optional(),
retryOnBlocked: z.boolean().default(false),
respectRobotsTxtFile: z.union([z.boolean(), schemas.anyObject]).default(false),
transactionalStorage: z
.union([z.boolean(), z.strictObject({ requestQueue: z.enum(['deferred', 'writeThrough']).optional() })])
.optional(),
onSkippedRequest: schemas.anyFunction.optional(),
httpClient: schemas.httpClient.optional(),
configuration: z.instanceof(Configuration).optional(),
storageBackend: validators.storageBackend.optional(),
eventManager: z.instanceof(EventManager).optional(),
logger: validators.logger.optional(),
// AutoscaledPool shorthands
minConcurrency: schemas.anyNumber.optional(),
maxConcurrency: schemas.anyNumber.optional(),
maxRequestsPerMinute: schemas.anyNumber
.refine((value) => Number.isInteger(value) || value === Infinity, 'Expected an integer or infinite number')
.refine((value) => value >= 1, 'Expected a number greater than or equal to 1')
.optional(),
keepAlive: z.boolean().optional(),
statistics: schemas.anyObject.optional(),
id: z.string().optional(),
};
static #optionsSchema = z.strictObject(BasicCrawler.optionsShape);
/**
* All `BasicCrawler` parameters are passed via an options object.
*/
constructor(
options: BasicCrawlerOptions<Context, ContextExtension, ExtendedContext, Routes, StatisticStateExtension> &
RequireContextPipeline<CrawlingContext, Context> = {} as any, // cast because the constructor logic handles missing `contextPipelineBuilder` - the type is just for DX
) {
const parsedOptions = parseArgument(options, BasicCrawler.#optionsSchema, 'BasicCrawlerOptions');
const {
// oxlint-disable-next-line typescript/no-deprecated -- still accepted and folded into `requestManager` for back-compat
requestList,
// oxlint-disable-next-line typescript/no-deprecated -- still accepted and folded into `requestManager` for back-compat
requestQueue,
requestManager,
maxRequestRetries,
sameDomainDelaySecs,
maxRequestsPerCrawl,
maxCrawlDepth,
taskLoopOptions = {},
concurrencySystem,
keepAlive,
sessionPool,
proxyConfiguration,
additionalHttpErrorStatusCodes,
ignoreHttpErrorStatusCodes,
// Service locator options
configuration,
storageBackend,
eventManager,
logger,
// AutoscaledPool shorthands
minConcurrency,
maxConcurrency,
maxRequestsPerMinute,
blockedStatusCodes: blockedStatusCodesInput,
retryOnBlocked,
respectRobotsTxtFile,
transactionalStorage,
onSkippedRequest,
requestHandler,
requestHandlerTimeoutSecs,