-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathbasic-crawler.ts
More file actions
2198 lines (1893 loc) · 88.8 KB
/
basic-crawler.ts
File metadata and controls
2198 lines (1893 loc) · 88.8 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 { dirname } from 'node:path';
import type {
AddRequestsBatchedOptions,
AddRequestsBatchedResult,
AutoscaledPoolOptions,
BaseHttpClient,
CrawlingContext,
DatasetExportOptions,
EnqueueLinksOptions,
EventManager,
FinalStatistics,
GetUserDataFromRequest,
IRequestList,
IRequestManager,
LoadedContext,
ProxyInfo,
Request,
RequestsLike,
RequestTransform,
RestrictedCrawlingContext,
RouterHandler,
RouterRoutes,
Session,
SessionPoolOptions,
SkippedRequestCallback,
Source,
StatisticsOptions,
StatisticState,
} from '@crawlee/core';
import {
AutoscaledPool,
Configuration,
CriticalError,
Dataset,
enqueueLinks,
EnqueueStrategy,
EventType,
GotScrapingHttpClient,
KeyValueStore,
mergeCookies,
Monitor,
type MonitorOptions,
NonRetryableError,
purgeDefaultStorages,
RequestListAdapter,
RequestManagerTandem,
RequestProvider,
RequestQueue,
RequestQueueV1,
RequestState,
RetryRequestError,
Router,
SessionError,
SessionPool,
Statistics,
validators,
} from '@crawlee/core';
import type { Awaitable, BatchAddRequestsResult, Dictionary, SetStatusMessageOptions } from '@crawlee/types';
import { getObjectType, isAsyncIterable, isIterable, RobotsTxtFile, ROTATE_PROXY_ERRORS } from '@crawlee/utils';
import { stringify } from 'csv-stringify/sync';
import { ensureDir, writeFile, writeJSON } from 'fs-extra';
import ow, { ArgumentError } from 'ow';
import { getDomain } from 'tldts';
import type { SetRequired } from 'type-fest';
import { LruCache } from '@apify/datastructures';
import type { Log } from '@apify/log';
import defaultLog, { LogLevel } from '@apify/log';
import { addTimeoutToPromise, TimeoutError, tryCancel } from '@apify/timeout';
import { cryptoRandomObjectId } from '@apify/utilities';
import { createSendRequest } from './send-request';
export interface BasicCrawlingContext<UserData extends Dictionary = Dictionary>
extends CrawlingContext<BasicCrawler, UserData> {
/**
* This function automatically finds and enqueues links from the current page, adding them to the {@apilink RequestQueue}
* currently used by the crawler.
*
* Optionally, the function allows you to filter the target links' URLs using an array of globs or regular expressions
* and override settings of the enqueued {@apilink Request} objects.
*
* Check out the [Crawl a website with relative links](https://crawlee.dev/js/docs/examples/crawl-relative-links) example
* for more details regarding its usage.
*
* **Example usage**
*
* ```ts
* async requestHandler({ enqueueLinks }) {
* await enqueueLinks({
* urls: [...],
* });
* },
* ```
*
* @param [options] All `enqueueLinks()` parameters are passed via an options object.
* @returns Promise that resolves to {@apilink BatchAddRequestsResult} object.
*/
enqueueLinks(options?: SetRequired<EnqueueLinksOptions, 'urls'>): Promise<BatchAddRequestsResult>;
}
/**
* 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;
export type RequestHandler<
Context extends CrawlingContext = LoadedContext<BasicCrawlingContext & RestrictedCrawlingContext>,
> = (inputs: LoadedContext<Context>) => Awaitable<void>;
export type ErrorHandler<
Context extends CrawlingContext = LoadedContext<BasicCrawlingContext & RestrictedCrawlingContext>,
> = (inputs: LoadedContext<Context>, 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 interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCrawlingContext> {
/**
* 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<LoadedContext<Context>>;
/**
* 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.
*
* @deprecated `handleRequestFunction` has been renamed to `requestHandler` and will be removed in a future version.
* @ignore
*/
handleRequestFunction?: RequestHandler<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;
/**
* Timeout in which the function passed as {@apilink BasicCrawlerOptions.requestHandler|`requestHandler`} needs to finish, in seconds.
* @default 60
* @deprecated `handleRequestTimeoutSecs` has been renamed to `requestHandlerTimeoutSecs` and will be removed in a future version.
* @ignore
*/
handleRequestTimeoutSecs?: 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<Context>;
/**
* 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<Context>;
/**
* 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.
*
* @deprecated `handleFailedRequestFunction` has been renamed to `failedRequestHandler` and will be removed in a future version.
* @ignore
*/
handleFailedRequestFunction?: ErrorHandler<Context>;
/**
* 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
* (`requestHandler`, `preNavigationHooks`, `postNavigationHooks`).
*
* This limit does not apply to retries triggered by session rotation
* (see {@apilink BasicCrawlerOptions.maxSessionRotations|`maxSessionRotations`}).
* @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 session rotations per request.
* The crawler will automatically rotate the session in case of a proxy error or if it gets blocked by the website.
*
* The session rotations are not counted towards the {@apilink BasicCrawlerOptions.maxRequestRetries|`maxRequestRetries`} limit.
* @default 10
*/
maxSessionRotations?: 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;
/**
* Basic crawler will initialize the {@apilink SessionPool} with the corresponding {@apilink SessionPoolOptions|`sessionPoolOptions`}.
* The session instance will be than available in the {@apilink BasicCrawlerOptions.requestHandler|`requestHandler`}.
*/
useSessionPool?: boolean;
/**
* The configuration options for {@apilink SessionPool} to use.
*/
sessionPoolOptions?: SessionPoolOptions;
/**
* 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;
/**
* 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;
/** @internal */
log?: Log;
/**
* 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;
/**
* Enables monitor mode: a compact real-time status block printed to `process.stderr` during the crawl.
*
* In interactive terminals (TTY), the block overwrites itself in-place.
* In non-TTY environments (CI, piped output), plain lines are printed instead.
*
* @default false
* @example
* ```ts
* const crawler = new BasicCrawler({ monitor: true });
* ```
*/
monitor?: boolean;
/**
* Options for the monitor display. Only used when `monitor` is `true`.
*/
monitorOptions?: MonitorOptions;
}
/**
* 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 = BasicCrawlingContext> {
protected static readonly CRAWLEE_STATE_KEY = 'CRAWLEE_STATE';
/**
* 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 {@apilink SessionPool} class that manages the crawler's {@apilink Session|sessions}.
* Only available if used by the crawler.
*/
sessionPool?: 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;
/**
* 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<LoadedContext<Context>> = Router.create<LoadedContext<Context>>();
running = false;
hasFinishedBefore = false;
protected unexpectedStop = false;
readonly log: Log;
protected requestHandler!: RequestHandler<Context>;
protected errorHandler?: ErrorHandler<Context>;
protected failedRequestHandler?: ErrorHandler<Context>;
protected requestHandlerTimeoutMillis!: number;
protected internalTimeoutMillis: number;
protected maxRequestRetries: number;
protected maxCrawlDepth?: number;
protected sameDomainDelayMillis: number;
protected domainAccessedTime: Map<string, number>;
protected maxSessionRotations: number;
protected maxRequestsPerCrawl?: number;
protected get handledRequestsCount(): number {
return this.stats.state.requestsFinished + this.stats.state.requestsFailed;
}
/** @deprecated Setting `handledRequestsCount` directly is no longer supported. The count is now derived from `this.stats`. */
protected set handledRequestsCount(_value: number) {
throw new Error(
'Setting `handledRequestsCount` directly is no longer supported. ' +
'The count is now derived from `this.stats.state.requestsFinished` and `this.stats.state.requestsFailed`.',
);
}
protected statusMessageLoggingInterval: number;
protected statusMessageCallback?: StatusMessageCallback;
protected sessionPoolOptions: SessionPoolOptions;
protected useSessionPool: boolean;
protected crawlingContexts = new Map<string, Context>();
protected autoscaledPoolOptions: AutoscaledPoolOptions;
protected events: EventManager;
protected httpClient: BaseHttpClient;
protected retryOnBlocked: boolean;
protected respectRobotsTxtFile: boolean | { userAgent?: string };
protected onSkippedRequest?: SkippedRequestCallback;
protected monitorEnabled: boolean;
protected monitorOptions: MonitorOptions;
private _closeEvents?: boolean;
private loggedPerRun = new Set<string>();
private experiments: CrawlerExperiments;
private readonly robotsTxtFileCache: LruCache<RobotsTxtFile>;
private _experimentWarnings: Partial<Record<keyof CrawlerExperiments, boolean>> = {};
protected static optionsShape = {
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,
// TODO: remove in a future release
handleRequestFunction: ow.optional.function,
requestHandlerTimeoutSecs: ow.optional.number,
// TODO: remove in a future release
handleRequestTimeoutSecs: ow.optional.number,
errorHandler: ow.optional.function,
failedRequestHandler: ow.optional.function,
// TODO: remove in a future release
handleFailedRequestFunction: ow.optional.function,
maxRequestRetries: ow.optional.number,
sameDomainDelaySecs: ow.optional.number,
maxSessionRotations: ow.optional.number,
maxRequestsPerCrawl: ow.optional.number,
maxCrawlDepth: ow.optional.number,
autoscaledPoolOptions: ow.optional.object,
sessionPoolOptions: ow.optional.object,
useSessionPool: ow.optional.boolean,
statusMessageLoggingInterval: ow.optional.number,
statusMessageCallback: ow.optional.function,
retryOnBlocked: ow.optional.boolean,
respectRobotsTxtFile: ow.optional.any(ow.boolean, ow.object),
onSkippedRequest: ow.optional.function,
httpClient: ow.optional.object,
monitor: ow.optional.boolean,
monitorOptions: 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
log: ow.optional.object,
experiments: ow.optional.object,
statisticsOptions: ow.optional.object,
};
/**
* All `BasicCrawler` parameters are passed via an options object.
*/
constructor(
options: BasicCrawlerOptions<Context> = {},
readonly config = Configuration.getGlobalConfig(),
) {
ow(options, 'BasicCrawlerOptions', ow.object.exactShape(BasicCrawler.optionsShape));
const {
requestList,
requestQueue,
requestManager,
maxRequestRetries = 3,
sameDomainDelaySecs = 0,
maxSessionRotations = 10,
maxRequestsPerCrawl,
maxCrawlDepth,
autoscaledPoolOptions = {},
keepAlive,
sessionPoolOptions = {},
useSessionPool = true,
// AutoscaledPool shorthands
minConcurrency,
maxConcurrency,
maxRequestsPerMinute,
retryOnBlocked = false,
respectRobotsTxtFile = false,
onSkippedRequest,
// internal
log = defaultLog.child({ prefix: this.constructor.name }),
experiments = {},
// Old and new request handler methods
handleRequestFunction,
requestHandler,
handleRequestTimeoutSecs,
requestHandlerTimeoutSecs,
errorHandler,
handleFailedRequestFunction,
failedRequestHandler,
statusMessageLoggingInterval = 10,
statusMessageCallback,
statisticsOptions,
httpClient,
monitor: monitorEnabled = false,
monitorOptions = {},
} = options;
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();
this.log = log;
this.monitorEnabled = monitorEnabled;
this.monitorOptions = monitorOptions;
this.statusMessageLoggingInterval = statusMessageLoggingInterval;
this.statusMessageCallback = statusMessageCallback as StatusMessageCallback;
this.events = config.getEventManager();
this.domainAccessedTime = new Map();
this.experiments = experiments;
this.robotsTxtFileCache = new LruCache({ maxLength: 1000 });
this.handleSkippedRequest = this.handleSkippedRequest.bind(this);
this._handlePropertyNameChange({
newName: 'requestHandler',
oldName: 'handleRequestFunction',
propertyKey: 'requestHandler',
newProperty: requestHandler,
oldProperty: handleRequestFunction,
allowUndefined: true, // fallback to the default router
});
if (!this.requestHandler) {
this.requestHandler = this.router;
}
this.errorHandler = errorHandler;
this._handlePropertyNameChange({
newName: 'failedRequestHandler',
oldName: 'handleFailedRequestFunction',
propertyKey: 'failedRequestHandler',
newProperty: failedRequestHandler,
oldProperty: handleFailedRequestFunction,
allowUndefined: true,
});
let newRequestHandlerTimeout: number | undefined;
if (!handleRequestTimeoutSecs) {
if (!requestHandlerTimeoutSecs) {
newRequestHandlerTimeout = 60_000;
} else {
newRequestHandlerTimeout = requestHandlerTimeoutSecs * 1000;
}
} else if (requestHandlerTimeoutSecs) {
newRequestHandlerTimeout = requestHandlerTimeoutSecs * 1000;
}
this.retryOnBlocked = retryOnBlocked;
this.respectRobotsTxtFile = respectRobotsTxtFile;
this.onSkippedRequest = onSkippedRequest;
this._handlePropertyNameChange({
newName: 'requestHandlerTimeoutSecs',
oldName: 'handleRequestTimeoutSecs',
propertyKey: 'requestHandlerTimeoutMillis',
newProperty: newRequestHandlerTimeout,
oldProperty: handleRequestTimeoutSecs ? handleRequestTimeoutSecs * 1000 : undefined,
});
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.maxSessionRotations = maxSessionRotations;
this.stats = new Statistics({
logMessage: `${log.getOptions().prefix} request statistics:`,
log,
config,
...statisticsOptions,
});
this.sessionPoolOptions = {
...sessionPoolOptions,
log,
};
if (this.retryOnBlocked) {
this.sessionPoolOptions.blockedStatusCodes = sessionPoolOptions.blockedStatusCodes ?? [];
if (this.sessionPoolOptions.blockedStatusCodes.length !== 0) {
log.warning(
`Both 'blockedStatusCodes' and 'retryOnBlocked' are set. Please note that the 'retryOnBlocked' feature might not work as expected.`,
);
}
}
this.useSessionPool = useSessionPool;
this.crawlingContexts = new Map();
const maxSignedInteger = 2 ** 31 - 1;
if (this.requestHandlerTimeoutMillis > maxSignedInteger) {
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: this._runTaskFunction.bind(this),
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()) {
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.`,
);
return true;
}
if (this.unexpectedStop) {
this.log.info(
'The crawler has finished all the remaining ongoing requests and will shut down now.',
);
return true;
}
const isFinished = isFinishedFunction
? await isFinishedFunction()
: await this._defaultIsFinishedFunction();
if (isFinished) {
const reason = isFinishedFunction
? "Crawler's custom isFinishedFunction() returned true, the crawler will shut down."
: 'All requests from the queue have been processed, the crawler will shut down.';
log.info(reason);
}
return isFinished;
},
log,
};
this.autoscaledPoolOptions = { ...autoscaledPoolOptions, ...basicCrawlerAutoscaledPoolConfiguration };
}
/**
* Checks if the given error is a proxy error by comparing its message to a list of known proxy error messages.
* Used for retrying requests that failed due to proxy errors.
*
* @param error The error to check.
*/
protected isProxyError(error: Error): boolean {
return ROTATE_PROXY_ERRORS.some((x: string) => (this._getMessageFromError(error) as any)?.includes(x));
}
/**
* Checks whether the given crawling context is getting blocked by anti-bot protection using several heuristics.
* Returns `false` if the request is not blocked, otherwise returns a string with a description of the block reason.
* @param _crawlingContext The crawling context to check.
*/
protected async isRequestBlocked(_crawlingContext: Context): Promise<string | false> {
throw new Error('the "isRequestBlocked" method is not implemented in this crawler.');
}
/**
* This method is periodically called by the crawler, every `statusMessageLoggingInterval` seconds.
*/
async setStatusMessage(message: string, options: SetStatusMessageOptions = {}) {
const data =
options.isStatusMessageTerminal != null ? { terminal: options.isStatusMessageTerminal } : undefined;
this.log.internal(LogLevel[(options.level as 'DEBUG') ?? 'DEBUG'], message, data);
const client = this.config.getStorageClient();
if (!client.setStatusMessage) {
return;
}
// just to be sure, this should be fast
await addTimeoutToPromise(
async () => client.setStatusMessage!(message, options),
1000,
'Setting status message timed out after 1s',
).catch((e) => this.log.debug(e.message));
}
private getPeriodicLogger() {
let previousState = { ...this.stats.state };
const getOperationMode = (): { mode: 'ERROR' | 'REGULAR'; failedDelta: number } => {
const { requestsFailed } = this.stats.state;
const { requestsFailed: previousRequestsFailed } = previousState;
previousState = { ...this.stats.state };
const failedDelta = requestsFailed - previousRequestsFailed;
if (failedDelta > 0) {
return { mode: 'ERROR', failedDelta };
}
return { mode: 'REGULAR', failedDelta: 0 };
};
const log = async () => {
// When monitor mode is active, it owns the display — skip the periodic log to avoid
// interleaving plain log lines with ANSI cursor-movement sequences.
if (this.monitorEnabled) return;
const { mode: operationMode, failedDelta } = getOperationMode();
let message: string;
if (operationMode === 'ERROR') {
message = `Experiencing problems, ${failedDelta} failed requests in the past ${this.statusMessageLoggingInterval} seconds.`;
} else {
const total = this.requestManager?.getTotalCount();
message = `Crawled ${this.stats.state.requestsFinished}${total ? `/${total}` : ''} pages, ${
this.stats.state.requestsFailed
} failed requests, desired concurrency ${this.autoscaledPool?.desiredConcurrency ?? 0}.`;
}
if (this.statusMessageCallback) {
await this.statusMessageCallback({
crawler: this as any,
state: this.stats.state,
previousState,
message,
});
return;
}
await this.setStatusMessage(message);
};
const interval = setInterval(log, this.statusMessageLoggingInterval * 1e3);
return { log, stop: () => clearInterval(interval) };
}