@crawlee/basic 4.0.0-beta.4 → 4.0.0-beta.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -5
- package/index.d.ts +1 -1
- package/index.d.ts.map +1 -1
- package/index.js +0 -1
- package/index.js.map +1 -1
- package/internals/basic-crawler.d.ts +270 -102
- package/internals/basic-crawler.d.ts.map +1 -1
- package/internals/basic-crawler.js +666 -330
- package/internals/basic-crawler.js.map +1 -1
- package/internals/send-request.d.ts +3 -5
- package/internals/send-request.d.ts.map +1 -1
- package/internals/send-request.js +21 -25
- package/internals/send-request.js.map +1 -1
- package/package.json +6 -6
- package/internals/constants.d.ts +0 -7
- package/internals/constants.d.ts.map +0 -1
- package/internals/constants.js +0 -7
- package/internals/constants.js.map +0 -1
- package/tsconfig.build.tsbuildinfo +0 -1
|
@@ -1,38 +1,13 @@
|
|
|
1
|
-
import type { AddRequestsBatchedOptions, AddRequestsBatchedResult, AutoscaledPoolOptions,
|
|
2
|
-
import { AutoscaledPool,
|
|
3
|
-
import type { Awaitable, BatchAddRequestsResult, Dictionary, SetStatusMessageOptions } from '@crawlee/types';
|
|
1
|
+
import type { AddRequestsBatchedOptions, AddRequestsBatchedResult, AutoscaledPoolOptions, Configuration, CrawleeLogger, CrawlingContext, DatasetExportOptions, EnqueueLinksOptions, EventManager, FinalStatistics, GetUserDataFromRequest, IRequestList, IRequestManager, ProxyConfiguration, Request, RequestsLike, RouterHandler, RouterRoutes, Session, SessionPoolOptions, SkippedRequestCallback, Source, StatisticsOptions, StatisticState } from '@crawlee/core';
|
|
2
|
+
import { AutoscaledPool, ContextPipeline, Dataset, RequestProvider, SessionPool, Statistics } from '@crawlee/core';
|
|
3
|
+
import type { Awaitable, BaseHttpClient, BatchAddRequestsResult, Dictionary, ProxyInfo, SetStatusMessageOptions, StorageClient } from '@crawlee/types';
|
|
4
4
|
import { RobotsTxtFile } from '@crawlee/utils';
|
|
5
|
-
import type { SetRequired } from 'type-fest';
|
|
6
|
-
import type { Log } from '@apify/log';
|
|
5
|
+
import type { ReadonlyDeep, SetRequired } from 'type-fest';
|
|
7
6
|
import { TimeoutError } from '@apify/timeout';
|
|
8
|
-
export interface BasicCrawlingContext<UserData extends Dictionary = Dictionary> extends CrawlingContext<
|
|
9
|
-
/**
|
|
10
|
-
* This function automatically finds and enqueues links from the current page, adding them to the {@link RequestQueue}
|
|
11
|
-
* currently used by the crawler.
|
|
12
|
-
*
|
|
13
|
-
* Optionally, the function allows you to filter the target links' URLs using an array of globs or regular expressions
|
|
14
|
-
* and override settings of the enqueued {@link Request} objects.
|
|
15
|
-
*
|
|
16
|
-
* Check out the [Crawl a website with relative links](https://crawlee.dev/js/docs/examples/crawl-relative-links) example
|
|
17
|
-
* for more details regarding its usage.
|
|
18
|
-
*
|
|
19
|
-
* **Example usage**
|
|
20
|
-
*
|
|
21
|
-
* ```ts
|
|
22
|
-
* async requestHandler({ enqueueLinks }) {
|
|
23
|
-
* await enqueueLinks({
|
|
24
|
-
* urls: [...],
|
|
25
|
-
* });
|
|
26
|
-
* },
|
|
27
|
-
* ```
|
|
28
|
-
*
|
|
29
|
-
* @param [options] All `enqueueLinks()` parameters are passed via an options object.
|
|
30
|
-
* @returns Promise that resolves to {@link BatchAddRequestsResult} object.
|
|
31
|
-
*/
|
|
32
|
-
enqueueLinks(options?: SetRequired<EnqueueLinksOptions, 'urls'>): Promise<BatchAddRequestsResult>;
|
|
7
|
+
export interface BasicCrawlingContext<UserData extends Dictionary = Dictionary> extends CrawlingContext<UserData> {
|
|
33
8
|
}
|
|
34
|
-
export type RequestHandler<Context extends CrawlingContext =
|
|
35
|
-
export type ErrorHandler<Context extends CrawlingContext =
|
|
9
|
+
export type RequestHandler<Context extends CrawlingContext = CrawlingContext> = (inputs: Context) => Awaitable<void>;
|
|
10
|
+
export type ErrorHandler<Context extends CrawlingContext = CrawlingContext, ExtendedContext extends Context = Context> = (inputs: Context & Partial<ExtendedContext>, error: Error) => Awaitable<void>;
|
|
36
11
|
export interface StatusMessageCallbackParams<Context extends CrawlingContext = BasicCrawlingContext, Crawler extends BasicCrawler<any> = BasicCrawler<Context>> {
|
|
37
12
|
state: StatisticState;
|
|
38
13
|
crawler: Crawler;
|
|
@@ -40,7 +15,10 @@ export interface StatusMessageCallbackParams<Context extends CrawlingContext = B
|
|
|
40
15
|
message: string;
|
|
41
16
|
}
|
|
42
17
|
export type StatusMessageCallback<Context extends CrawlingContext = BasicCrawlingContext, Crawler extends BasicCrawler<any> = BasicCrawler<Context>> = (params: StatusMessageCallbackParams<Context, Crawler>) => Awaitable<void>;
|
|
43
|
-
export
|
|
18
|
+
export type RequireContextPipeline<DefaultContextType extends CrawlingContext, FinalContextType extends DefaultContextType> = DefaultContextType extends FinalContextType ? {} : {
|
|
19
|
+
contextPipelineBuilder: () => ContextPipeline<CrawlingContext, FinalContextType>;
|
|
20
|
+
};
|
|
21
|
+
export interface BasicCrawlerOptions<Context extends CrawlingContext = CrawlingContext, ContextExtension = Dictionary<never>, ExtendedContext extends Context = Context & ContextExtension> {
|
|
44
22
|
/**
|
|
45
23
|
* User-provided function that performs the logic of the crawler. It is called for each URL to crawl.
|
|
46
24
|
*
|
|
@@ -58,7 +36,35 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
|
|
|
58
36
|
* The exceptions are logged to the request using the
|
|
59
37
|
* {@link Request.pushErrorMessage|`Request.pushErrorMessage()`} function.
|
|
60
38
|
*/
|
|
61
|
-
requestHandler?: RequestHandler<
|
|
39
|
+
requestHandler?: RequestHandler<ExtendedContext>;
|
|
40
|
+
/**
|
|
41
|
+
* Allows the user to extend the crawling context passed to the request handler with custom functionality.
|
|
42
|
+
*
|
|
43
|
+
* **Example usage:**
|
|
44
|
+
*
|
|
45
|
+
* ```javascript
|
|
46
|
+
* import { BasicCrawler } from 'crawlee';
|
|
47
|
+
*
|
|
48
|
+
* // Create a crawler instance
|
|
49
|
+
* const crawler = new BasicCrawler({
|
|
50
|
+
* extendContext(context) => ({
|
|
51
|
+
* async customHelper() {
|
|
52
|
+
* await context.pushData({ url: context.request.url })
|
|
53
|
+
* }
|
|
54
|
+
* }),
|
|
55
|
+
* async requestHandler(context) {
|
|
56
|
+
* await context.customHelper();
|
|
57
|
+
* },
|
|
58
|
+
* });
|
|
59
|
+
* ```
|
|
60
|
+
*/
|
|
61
|
+
extendContext?: (context: Context) => Awaitable<ContextExtension>;
|
|
62
|
+
/**
|
|
63
|
+
* *Intended for BasicCrawler subclasses*. Prepares a context pipeline that transforms the initial crawling context into the shape given by the `Context` type parameter.
|
|
64
|
+
*
|
|
65
|
+
* The option is not required if your crawler subclass does not extend the crawling context with custom information or helpers.
|
|
66
|
+
*/
|
|
67
|
+
contextPipelineBuilder?: () => ContextPipeline<CrawlingContext, Context>;
|
|
62
68
|
/**
|
|
63
69
|
* Static list of URLs to be processed.
|
|
64
70
|
* If not provided, the crawler will open the default request queue when the {@link BasicCrawler.addRequests|`crawler.addRequests()`} function is called.
|
|
@@ -73,6 +79,13 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
|
|
|
73
79
|
* it is a shortcut for running `crawler.addRequests()` before the `crawler.run()`.
|
|
74
80
|
*/
|
|
75
81
|
requestQueue?: RequestProvider;
|
|
82
|
+
/**
|
|
83
|
+
* Allows explicitly configuring a request manager. Mutually exclusive with the `requestQueue` and `requestList` options.
|
|
84
|
+
*
|
|
85
|
+
* This enables explicitly configuring the crawler to use `RequestManagerTandem`, for instance.
|
|
86
|
+
* If using this, the type of `BasicCrawler.requestQueue` may not be fully compatible with the `RequestProvider` class.
|
|
87
|
+
*/
|
|
88
|
+
requestManager?: IRequestManager;
|
|
76
89
|
/**
|
|
77
90
|
* Timeout in which the function passed as {@link BasicCrawlerOptions.requestHandler|`requestHandler`} needs to finish, in seconds.
|
|
78
91
|
* @default 60
|
|
@@ -87,7 +100,7 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
|
|
|
87
100
|
* Second argument is the `Error` instance that
|
|
88
101
|
* represents the last error thrown during processing of the request.
|
|
89
102
|
*/
|
|
90
|
-
errorHandler?: ErrorHandler<
|
|
103
|
+
errorHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;
|
|
91
104
|
/**
|
|
92
105
|
* A function to handle requests that failed more than {@link BasicCrawlerOptions.maxRequestRetries|`maxRequestRetries`} times.
|
|
93
106
|
*
|
|
@@ -96,7 +109,7 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
|
|
|
96
109
|
* Second argument is the `Error` instance that
|
|
97
110
|
* represents the last error thrown during processing of the request.
|
|
98
111
|
*/
|
|
99
|
-
failedRequestHandler?: ErrorHandler<
|
|
112
|
+
failedRequestHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;
|
|
100
113
|
/**
|
|
101
114
|
* Specifies the maximum number of retries allowed for a request if its processing fails.
|
|
102
115
|
* This includes retries due to navigation errors or errors thrown from user-supplied functions
|
|
@@ -126,12 +139,18 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
|
|
|
126
139
|
* > *NOTE:* In cases of parallel crawling, the actual number of pages visited might be slightly higher than this value.
|
|
127
140
|
*/
|
|
128
141
|
maxRequestsPerCrawl?: number;
|
|
142
|
+
/**
|
|
143
|
+
* Maximum depth of the crawl. If not set, the crawl will continue until all requests are processed.
|
|
144
|
+
* Setting this to `0` will only process the initial requests, skipping all links enqueued by `crawlingContext.enqueueLinks` and `crawlingContext.addRequests`.
|
|
145
|
+
* Passing `1` will process the initial requests and all links enqueued by `crawlingContext.enqueueLinks` and `crawlingContext.addRequests` in the handler for initial requests.
|
|
146
|
+
*/
|
|
147
|
+
maxCrawlDepth?: number;
|
|
129
148
|
/**
|
|
130
149
|
* Custom options passed to the underlying {@link AutoscaledPool} constructor.
|
|
131
150
|
* > *NOTE:* The {@link AutoscaledPoolOptions.runTaskFunction|`runTaskFunction`}
|
|
132
|
-
* and
|
|
133
|
-
*
|
|
134
|
-
*
|
|
151
|
+
* option is provided by the crawler and cannot be overridden.
|
|
152
|
+
* However, we can provide custom implementations of {@link AutoscaledPoolOptions.isFinishedFunction|`isFinishedFunction`}
|
|
153
|
+
* and {@link AutoscaledPoolOptions.isTaskReadyFunction|`isTaskReadyFunction`}.
|
|
135
154
|
*/
|
|
136
155
|
autoscaledPoolOptions?: AutoscaledPoolOptions;
|
|
137
156
|
/**
|
|
@@ -158,11 +177,6 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
|
|
|
158
177
|
* waiting for more requests to come. Use `crawler.stop()` to exit the crawler gracefully, or `crawler.teardown()` to stop it immediately.
|
|
159
178
|
*/
|
|
160
179
|
keepAlive?: boolean;
|
|
161
|
-
/**
|
|
162
|
-
* Basic crawler will initialize the {@link SessionPool} with the corresponding {@link SessionPoolOptions|`sessionPoolOptions`}.
|
|
163
|
-
* The session instance will be than available in the {@link BasicCrawlerOptions.requestHandler|`requestHandler`}.
|
|
164
|
-
*/
|
|
165
|
-
useSessionPool?: boolean;
|
|
166
180
|
/**
|
|
167
181
|
* The configuration options for {@link SessionPool} to use.
|
|
168
182
|
*/
|
|
@@ -188,6 +202,11 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
|
|
|
188
202
|
* ```
|
|
189
203
|
*/
|
|
190
204
|
statusMessageCallback?: StatusMessageCallback;
|
|
205
|
+
/**
|
|
206
|
+
* HTTP status codes that indicate the session should be retired.
|
|
207
|
+
* @default [401, 403, 429]
|
|
208
|
+
*/
|
|
209
|
+
blockedStatusCodes?: number[];
|
|
191
210
|
/**
|
|
192
211
|
* If set to `true`, the crawler will automatically try to bypass any detected bot protection.
|
|
193
212
|
*
|
|
@@ -199,15 +218,22 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
|
|
|
199
218
|
/**
|
|
200
219
|
* If set to `true`, the crawler will automatically try to fetch the robots.txt file for each domain,
|
|
201
220
|
* and skip those that are not allowed. This also prevents disallowed URLs to be added via `enqueueLinks`.
|
|
221
|
+
*
|
|
222
|
+
* If an object is provided, it may contain a `userAgent` property to specify which user-agent
|
|
223
|
+
* should be used when checking the robots.txt file. If not provided, the default user-agent `*` will be used.
|
|
202
224
|
*/
|
|
203
|
-
respectRobotsTxtFile?: boolean
|
|
225
|
+
respectRobotsTxtFile?: boolean | {
|
|
226
|
+
userAgent?: string;
|
|
227
|
+
};
|
|
204
228
|
/**
|
|
205
229
|
* When a request is skipped for some reason, you can use this callback to act on it.
|
|
206
|
-
* This is currently fired
|
|
230
|
+
* This is currently fired for requests skipped
|
|
231
|
+
* 1. based on robots.txt file,
|
|
232
|
+
* 2. because they don't match enqueueLinks filters,
|
|
233
|
+
* 3. because they are redirected to a URL that doesn't match the enqueueLinks strategy,
|
|
234
|
+
* 4. or because the {@link BasicCrawlerOptions.maxRequestsPerCrawl|`maxRequestsPerCrawl`} limit has been reached
|
|
207
235
|
*/
|
|
208
236
|
onSkippedRequest?: SkippedRequestCallback;
|
|
209
|
-
/** @internal */
|
|
210
|
-
log?: Log;
|
|
211
237
|
/**
|
|
212
238
|
* Enables experimental features of Crawlee, which can alter the behavior of the crawler.
|
|
213
239
|
* WARNING: these options are not guaranteed to be stable and may change or be removed at any time.
|
|
@@ -223,6 +249,53 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
|
|
|
223
249
|
* Defaults to a new instance of {@link GotScrapingHttpClient}
|
|
224
250
|
*/
|
|
225
251
|
httpClient?: BaseHttpClient;
|
|
252
|
+
/**
|
|
253
|
+
* If set, the crawler will be configured for all connections to use
|
|
254
|
+
* the Proxy URLs provided and rotated according to the configuration.
|
|
255
|
+
*/
|
|
256
|
+
proxyConfiguration?: ProxyConfiguration;
|
|
257
|
+
/**
|
|
258
|
+
* Custom configuration to use for this crawler.
|
|
259
|
+
* If provided, the crawler will use its own ServiceLocator instance instead of the global one.
|
|
260
|
+
*/
|
|
261
|
+
configuration?: Configuration;
|
|
262
|
+
/**
|
|
263
|
+
* Custom storage client to use for this crawler.
|
|
264
|
+
* If provided, the crawler will use its own ServiceLocator instance instead of the global one.
|
|
265
|
+
*/
|
|
266
|
+
storageClient?: StorageClient;
|
|
267
|
+
/**
|
|
268
|
+
* Custom event manager to use for this crawler.
|
|
269
|
+
* If provided, the crawler will use its own ServiceLocator instance instead of the global one.
|
|
270
|
+
*/
|
|
271
|
+
eventManager?: EventManager;
|
|
272
|
+
/**
|
|
273
|
+
* Custom logger to use for this crawler.
|
|
274
|
+
* If provided, the crawler will use its own ServiceLocator instance instead of the global one.
|
|
275
|
+
*/
|
|
276
|
+
logger?: CrawleeLogger;
|
|
277
|
+
/**
|
|
278
|
+
* A unique identifier for the crawler instance. This ID is used to isolate the state returned by
|
|
279
|
+
* {@link BasicCrawler.useState|`crawler.useState()`} from other crawler instances.
|
|
280
|
+
*
|
|
281
|
+
* When multiple crawler instances use `useState()` without an explicit `id`, they will share the same
|
|
282
|
+
* state object for backward compatibility. A warning will be logged in this case.
|
|
283
|
+
*
|
|
284
|
+
* To ensure each crawler has its own isolated state that also persists across script restarts
|
|
285
|
+
* (e.g., during Apify migrations), provide a stable, unique ID for each crawler instance.
|
|
286
|
+
*
|
|
287
|
+
*/
|
|
288
|
+
id?: string;
|
|
289
|
+
/**
|
|
290
|
+
* An array of HTTP response [Status Codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) to be excluded from error consideration.
|
|
291
|
+
* By default, status codes >= 500 trigger errors.
|
|
292
|
+
*/
|
|
293
|
+
ignoreHttpErrorStatusCodes?: number[];
|
|
294
|
+
/**
|
|
295
|
+
* An array of additional HTTP response [Status Codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) to be treated as errors.
|
|
296
|
+
* By default, status codes >= 500 trigger errors.
|
|
297
|
+
*/
|
|
298
|
+
additionalHttpErrorStatusCodes?: number[];
|
|
226
299
|
}
|
|
227
300
|
/**
|
|
228
301
|
* A set of options that you can toggle to enable experimental features in Crawlee.
|
|
@@ -303,9 +376,14 @@ export interface CrawlerExperiments {
|
|
|
303
376
|
* ```
|
|
304
377
|
* @category Crawlers
|
|
305
378
|
*/
|
|
306
|
-
export declare class BasicCrawler<Context extends CrawlingContext =
|
|
307
|
-
|
|
379
|
+
export declare class BasicCrawler<Context extends CrawlingContext = CrawlingContext, ContextExtension = Dictionary<never>, ExtendedContext extends Context = Context & ContextExtension> {
|
|
380
|
+
#private;
|
|
308
381
|
protected static readonly CRAWLEE_STATE_KEY = "CRAWLEE_STATE";
|
|
382
|
+
/**
|
|
383
|
+
* Tracks crawler instances that accessed shared state without having an explicit id.
|
|
384
|
+
* Used to detect and warn about multiple crawlers sharing the same state.
|
|
385
|
+
*/
|
|
386
|
+
private static useStateCrawlerIds;
|
|
309
387
|
/**
|
|
310
388
|
* A reference to the underlying {@link Statistics} class that collects and logs run statistics for requests.
|
|
311
389
|
*/
|
|
@@ -321,11 +399,14 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlin
|
|
|
321
399
|
* Only available if used by the crawler.
|
|
322
400
|
*/
|
|
323
401
|
requestQueue?: RequestProvider;
|
|
402
|
+
/**
|
|
403
|
+
* The main request-handling component of the crawler. It's initialized during the crawler startup.
|
|
404
|
+
*/
|
|
405
|
+
protected requestManager?: IRequestManager;
|
|
324
406
|
/**
|
|
325
407
|
* A reference to the underlying {@link SessionPool} class that manages the crawler's {@link Session|sessions}.
|
|
326
|
-
* Only available if used by the crawler.
|
|
327
408
|
*/
|
|
328
|
-
sessionPool
|
|
409
|
+
sessionPool: SessionPool;
|
|
329
410
|
/**
|
|
330
411
|
* A reference to the underlying {@link AutoscaledPool} class that manages the concurrency of the crawler.
|
|
331
412
|
* > *NOTE:* This property is only initialized after calling the {@link BasicCrawler.run|`crawler.run()`} function.
|
|
@@ -334,40 +415,72 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlin
|
|
|
334
415
|
* or to abort it by calling {@link AutoscaledPool.abort|`autoscaledPool.abort()`}.
|
|
335
416
|
*/
|
|
336
417
|
autoscaledPool?: AutoscaledPool;
|
|
418
|
+
/**
|
|
419
|
+
* A reference to the underlying {@link ProxyConfiguration} class that manages the crawler's proxies.
|
|
420
|
+
* Only available if used by the crawler.
|
|
421
|
+
*/
|
|
422
|
+
proxyConfiguration?: ProxyConfiguration;
|
|
337
423
|
/**
|
|
338
424
|
* Default {@link Router} instance that will be used if we don't specify any {@link BasicCrawlerOptions.requestHandler|`requestHandler`}.
|
|
339
425
|
* See {@link Router.addHandler|`router.addHandler()`} and {@link Router.addDefaultHandler|`router.addDefaultHandler()`}.
|
|
340
426
|
*/
|
|
341
|
-
readonly router: RouterHandler<
|
|
427
|
+
readonly router: RouterHandler<Context>;
|
|
428
|
+
private _basicContextPipeline?;
|
|
429
|
+
/**
|
|
430
|
+
* The basic part of the context pipeline. Unlike the subclass pipeline, this
|
|
431
|
+
* part has no major side effects (e.g. launching a browser). It also makes typing more explicit, as subclass
|
|
432
|
+
* pipelines expect the basic crawler fields to already be present in the context at runtime.
|
|
433
|
+
*
|
|
434
|
+
* Context built with this pipeline can be passed into multiple crawler pipelines at once.
|
|
435
|
+
* This is used e.g. in the {@link AdaptivePlaywrightCrawler|`AdaptivePlaywrightCrawler`}.
|
|
436
|
+
*/
|
|
437
|
+
get basicContextPipeline(): ContextPipeline<{
|
|
438
|
+
request: Request;
|
|
439
|
+
}, CrawlingContext>;
|
|
440
|
+
private _contextPipeline?;
|
|
441
|
+
get contextPipeline(): ContextPipeline<CrawlingContext, ExtendedContext>;
|
|
342
442
|
running: boolean;
|
|
343
443
|
hasFinishedBefore: boolean;
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
protected
|
|
347
|
-
protected
|
|
444
|
+
protected unexpectedStop: boolean;
|
|
445
|
+
get log(): CrawleeLogger;
|
|
446
|
+
protected requestHandler: RequestHandler<ExtendedContext>;
|
|
447
|
+
protected errorHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;
|
|
448
|
+
protected failedRequestHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;
|
|
348
449
|
protected requestHandlerTimeoutMillis: number;
|
|
349
450
|
protected internalTimeoutMillis: number;
|
|
350
451
|
protected maxRequestRetries: number;
|
|
452
|
+
protected maxCrawlDepth?: number;
|
|
351
453
|
protected sameDomainDelayMillis: number;
|
|
352
454
|
protected domainAccessedTime: Map<string, number>;
|
|
353
455
|
protected maxSessionRotations: number;
|
|
456
|
+
protected maxRequestsPerCrawl?: number;
|
|
354
457
|
protected handledRequestsCount: number;
|
|
355
458
|
protected statusMessageLoggingInterval: number;
|
|
356
459
|
protected statusMessageCallback?: StatusMessageCallback;
|
|
357
|
-
protected sessionPoolOptions
|
|
358
|
-
protected
|
|
359
|
-
protected
|
|
460
|
+
protected sessionPoolOptions?: SessionPoolOptions;
|
|
461
|
+
protected blockedStatusCodes: Set<number>;
|
|
462
|
+
protected additionalHttpErrorStatusCodes: Set<number>;
|
|
463
|
+
protected ignoreHttpErrorStatusCodes: Set<number>;
|
|
360
464
|
protected autoscaledPoolOptions: AutoscaledPoolOptions;
|
|
361
|
-
protected events: EventManager;
|
|
362
465
|
protected httpClient: BaseHttpClient;
|
|
363
466
|
protected retryOnBlocked: boolean;
|
|
364
|
-
protected respectRobotsTxtFile: boolean
|
|
467
|
+
protected respectRobotsTxtFile: boolean | {
|
|
468
|
+
userAgent?: string;
|
|
469
|
+
};
|
|
365
470
|
protected onSkippedRequest?: SkippedRequestCallback;
|
|
366
471
|
private _closeEvents?;
|
|
472
|
+
private loggedPerRun;
|
|
367
473
|
private experiments;
|
|
368
474
|
private readonly robotsTxtFileCache;
|
|
369
475
|
private _experimentWarnings;
|
|
476
|
+
private readonly crawlerId;
|
|
477
|
+
private readonly hasExplicitId;
|
|
478
|
+
private readonly contextPipelineOptions;
|
|
370
479
|
protected static optionsShape: {
|
|
480
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
481
|
+
contextPipelineBuilder: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
482
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
483
|
+
extendContext: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
|
|
371
484
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
372
485
|
requestList: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
373
486
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
@@ -388,24 +501,40 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlin
|
|
|
388
501
|
maxSessionRotations: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
|
|
389
502
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
390
503
|
maxRequestsPerCrawl: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
|
|
504
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
505
|
+
maxCrawlDepth: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
|
|
391
506
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
392
507
|
autoscaledPoolOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
393
508
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
394
509
|
sessionPoolOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
395
510
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
396
|
-
|
|
511
|
+
proxyConfiguration: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
397
512
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
398
513
|
statusMessageLoggingInterval: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
|
|
399
514
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
400
515
|
statusMessageCallback: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
|
|
516
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
517
|
+
additionalHttpErrorStatusCodes: import("ow").ArrayPredicate<number>;
|
|
518
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
519
|
+
ignoreHttpErrorStatusCodes: import("ow").ArrayPredicate<number>;
|
|
520
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
521
|
+
blockedStatusCodes: import("ow").ArrayPredicate<number>;
|
|
401
522
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
402
523
|
retryOnBlocked: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
|
|
403
524
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
404
|
-
respectRobotsTxtFile: import("ow").
|
|
525
|
+
respectRobotsTxtFile: import("ow").AnyPredicate<boolean | object>;
|
|
405
526
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
406
527
|
onSkippedRequest: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
|
|
407
528
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
408
529
|
httpClient: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
530
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
531
|
+
configuration: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
532
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
533
|
+
storageClient: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
534
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
535
|
+
eventManager: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
536
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
537
|
+
logger: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
409
538
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
410
539
|
minConcurrency: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
|
|
411
540
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
@@ -414,17 +543,42 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlin
|
|
|
414
543
|
maxRequestsPerMinute: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
|
|
415
544
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
416
545
|
keepAlive: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
|
|
417
|
-
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
418
|
-
log: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
419
546
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
420
547
|
experiments: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
421
548
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
422
549
|
statisticsOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
550
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
551
|
+
id: import("ow").StringPredicate & import("ow").BasePredicate<string | undefined>;
|
|
423
552
|
};
|
|
424
553
|
/**
|
|
425
554
|
* All `BasicCrawler` parameters are passed via an options object.
|
|
426
555
|
*/
|
|
427
|
-
constructor(options?: BasicCrawlerOptions<Context
|
|
556
|
+
constructor(options?: BasicCrawlerOptions<Context, ContextExtension, ExtendedContext> & RequireContextPipeline<CrawlingContext, Context>);
|
|
557
|
+
/**
|
|
558
|
+
* Determines if the given HTTP status code is an error status code given
|
|
559
|
+
* the default behaviour and user-set preferences.
|
|
560
|
+
* @param status
|
|
561
|
+
* @returns `true` if the status code is considered an error, `false` otherwise
|
|
562
|
+
*/
|
|
563
|
+
protected isErrorStatusCode(status: number): boolean;
|
|
564
|
+
/**
|
|
565
|
+
* Builds the basic context pipeline that transforms `{ request }` into a full `CrawlingContext`.
|
|
566
|
+
* This handles base context creation, session resolution, and context helpers.
|
|
567
|
+
*/
|
|
568
|
+
protected buildBasicContextPipeline(): ContextPipeline<{
|
|
569
|
+
request: Request;
|
|
570
|
+
}, CrawlingContext>;
|
|
571
|
+
private checkRobotsTxt;
|
|
572
|
+
/**
|
|
573
|
+
* Builds the subclass-specific context pipeline that transforms a `CrawlingContext` into the crawler's target context type.
|
|
574
|
+
* Subclasses should override this to add their own pipeline stages.
|
|
575
|
+
*/
|
|
576
|
+
protected buildContextPipeline(): ContextPipeline<CrawlingContext, CrawlingContext>;
|
|
577
|
+
private createBaseContext;
|
|
578
|
+
private resolveRequest;
|
|
579
|
+
private resolveSession;
|
|
580
|
+
private createContextHelpers;
|
|
581
|
+
private buildFinalContextPipeline;
|
|
428
582
|
/**
|
|
429
583
|
* Checks if the given error is a proxy error by comparing its message to a list of known proxy error messages.
|
|
430
584
|
* Used for retrying requests that failed due to proxy errors.
|
|
@@ -432,12 +586,6 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlin
|
|
|
432
586
|
* @param error The error to check.
|
|
433
587
|
*/
|
|
434
588
|
protected isProxyError(error: Error): boolean;
|
|
435
|
-
/**
|
|
436
|
-
* Checks whether the given crawling context is getting blocked by anti-bot protection using several heuristics.
|
|
437
|
-
* Returns `false` if the request is not blocked, otherwise returns a string with a description of the block reason.
|
|
438
|
-
* @param _crawlingContext The crawling context to check.
|
|
439
|
-
*/
|
|
440
|
-
protected isRequestBlocked(_crawlingContext: Context): Promise<string | false>;
|
|
441
589
|
/**
|
|
442
590
|
* This method is periodically called by the crawler, every `statusMessageLoggingInterval` seconds.
|
|
443
591
|
*/
|
|
@@ -453,15 +601,21 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlin
|
|
|
453
601
|
* @param [requests] The requests to add.
|
|
454
602
|
* @param [options] Options for the request queue.
|
|
455
603
|
*/
|
|
456
|
-
run(requests?:
|
|
604
|
+
run(requests?: RequestsLike, options?: CrawlerRunOptions): Promise<FinalStatistics>;
|
|
457
605
|
/**
|
|
458
606
|
* Gracefully stops the current run of the crawler.
|
|
459
607
|
*
|
|
460
608
|
* All the tasks active at the time of calling this method will be allowed to finish.
|
|
609
|
+
*
|
|
610
|
+
* To stop the crawler immediately, use {@link BasicCrawler.teardown|`crawler.teardown()`} instead.
|
|
461
611
|
*/
|
|
462
|
-
stop(
|
|
612
|
+
stop(reason?: string): void;
|
|
463
613
|
getRequestQueue(): Promise<RequestProvider>;
|
|
464
614
|
useState<State extends Dictionary = Dictionary>(defaultValue?: State): Promise<State>;
|
|
615
|
+
protected get pendingRequestCountApproximation(): number;
|
|
616
|
+
protected calculateEnqueuedRequestLimit(explicitLimit?: number): number | undefined;
|
|
617
|
+
protected handleSkippedRequest(options: Parameters<SkippedRequestCallback>[0]): Promise<void>;
|
|
618
|
+
private logOncePerRun;
|
|
465
619
|
/**
|
|
466
620
|
* Adds requests to the queue in batches. By default, it will resolve after the initial batch is added, and continue
|
|
467
621
|
* adding the rest in background. You can configure the batch size via `batchSize` option and the sleep time in between
|
|
@@ -473,7 +627,7 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlin
|
|
|
473
627
|
* @param requests The requests to add
|
|
474
628
|
* @param options Options for the request queue
|
|
475
629
|
*/
|
|
476
|
-
addRequests(requests:
|
|
630
|
+
addRequests(requests: ReadonlyDeep<RequestsLike>, options?: CrawlerAddRequestsOptions): Promise<CrawlerAddRequestsResult>;
|
|
477
631
|
/**
|
|
478
632
|
* Pushes data to the specified {@link Dataset}, or the default crawler {@link Dataset} by calling {@link Dataset.pushData}.
|
|
479
633
|
*/
|
|
@@ -491,41 +645,52 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlin
|
|
|
491
645
|
* Supported formats are currently 'json' and 'csv', and will be inferred from the `path` automatically.
|
|
492
646
|
*/
|
|
493
647
|
exportData<Data>(path: string, format?: 'json' | 'csv', options?: DatasetExportOptions): Promise<Data[]>;
|
|
648
|
+
/**
|
|
649
|
+
* Initializes the crawler.
|
|
650
|
+
*/
|
|
494
651
|
protected _init(): Promise<void>;
|
|
495
|
-
protected
|
|
652
|
+
protected runRequestHandler(crawlingContext: ExtendedContext): Promise<void>;
|
|
496
653
|
/**
|
|
497
654
|
* Handles blocked request
|
|
498
655
|
*/
|
|
499
|
-
protected _throwOnBlockedRequest(
|
|
656
|
+
protected _throwOnBlockedRequest(statusCode: number): void;
|
|
500
657
|
private isAllowedBasedOnRobotsTxtFile;
|
|
501
658
|
protected getRobotsTxtFileForUrl(url: string): Promise<RobotsTxtFile | undefined>;
|
|
502
659
|
protected _pauseOnMigration(): Promise<void>;
|
|
503
660
|
/**
|
|
504
|
-
*
|
|
505
|
-
* and RequestQueue is present then enqueues it to the queue first.
|
|
661
|
+
* Initializes the RequestManager based on the configured requestList and requestQueue.
|
|
506
662
|
*/
|
|
507
|
-
|
|
663
|
+
private initializeRequestManager;
|
|
508
664
|
/**
|
|
509
|
-
*
|
|
510
|
-
* Can be used to clean up orphaned browser pages.
|
|
665
|
+
* Fetches the next request to process from the underlying request provider.
|
|
511
666
|
*/
|
|
512
|
-
protected
|
|
667
|
+
protected _fetchNextRequest(): Promise<Request<Dictionary> | null>;
|
|
513
668
|
/**
|
|
514
669
|
* Delays processing of the request based on the `sameDomainDelaySecs` option,
|
|
515
670
|
* adding it back to the queue after the timeout passes. Returns `true` if the request
|
|
516
671
|
* should be ignored and will be reclaimed to the queue once ready.
|
|
517
672
|
*/
|
|
518
|
-
protected delayRequest(request: Request, source: IRequestList | RequestProvider): boolean;
|
|
673
|
+
protected delayRequest(request: Request, source: IRequestList | RequestProvider | IRequestManager): boolean;
|
|
674
|
+
/** Handles a single request - runs the request handler with retries, error handling, and lifecycle management. */
|
|
675
|
+
protected handleRequest(crawlingContext: ExtendedContext, requestSource: IRequestManager): Promise<void>;
|
|
676
|
+
/**
|
|
677
|
+
* Wrapper around the crawling context's `enqueueLinks` method:
|
|
678
|
+
* - Injects `crawlDepth` to each request being added based on the crawling context request.
|
|
679
|
+
* - Provides defaults for the `enqueueLinks` options based on the crawler configuration.
|
|
680
|
+
* - These options can be overridden by the user.
|
|
681
|
+
* @internal
|
|
682
|
+
*/
|
|
683
|
+
protected enqueueLinksWithCrawlDepth(options: SetRequired<EnqueueLinksOptions, 'urls'>, request: Request<Dictionary>, requestQueue: RequestProvider): Promise<BatchAddRequestsResult>;
|
|
519
684
|
/**
|
|
520
|
-
*
|
|
521
|
-
*
|
|
685
|
+
* Generator function that yields requests injected with the given crawl depth.
|
|
686
|
+
* @internal
|
|
522
687
|
*/
|
|
523
|
-
protected
|
|
688
|
+
protected addCrawlDepthRequestGenerator(requests: RequestsLike, newRequestDepth: number): AsyncGenerator<Source, void, undefined>;
|
|
524
689
|
/**
|
|
525
|
-
* Run async callback with given timeout and retry.
|
|
690
|
+
* Run async callback with given timeout and retry. Returns the result of the callback.
|
|
526
691
|
* @ignore
|
|
527
692
|
*/
|
|
528
|
-
protected _timeoutAndRetry(handler: () => Promise<
|
|
693
|
+
protected _timeoutAndRetry<T>(handler: () => Promise<T>, timeout: number, error: Error | string, maxRetries?: number, retried?: number): Promise<T>;
|
|
529
694
|
/**
|
|
530
695
|
* Returns true if either RequestList or RequestQueue have a request ready for processing.
|
|
531
696
|
*/
|
|
@@ -535,12 +700,17 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlin
|
|
|
535
700
|
*/
|
|
536
701
|
protected _defaultIsFinishedFunction(): Promise<boolean>;
|
|
537
702
|
private _rotateSession;
|
|
703
|
+
/**
|
|
704
|
+
* Unwraps errors thrown by the context pipeline to get the actual user error.
|
|
705
|
+
* RequestHandlerError and ContextPipelineInitializationError wrap the actual error.
|
|
706
|
+
*/
|
|
707
|
+
private unwrapError;
|
|
538
708
|
/**
|
|
539
709
|
* Handles errors thrown by user provided requestHandler()
|
|
540
710
|
*/
|
|
541
|
-
protected _requestFunctionErrorHandler(error: Error, crawlingContext:
|
|
711
|
+
protected _requestFunctionErrorHandler(error: Error, crawlingContext: CrawlingContext, source: IRequestList | IRequestManager): Promise<void>;
|
|
542
712
|
protected _tagUserHandlerError<T>(cb: () => unknown): Promise<T>;
|
|
543
|
-
protected _handleFailedRequestHandler(crawlingContext:
|
|
713
|
+
protected _handleFailedRequestHandler(crawlingContext: CrawlingContext, error: Error): Promise<void>;
|
|
544
714
|
/**
|
|
545
715
|
* Resolves the most verbose error message from a thrown error
|
|
546
716
|
* @param error The error received
|
|
@@ -549,27 +719,25 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlin
|
|
|
549
719
|
protected _getMessageFromError(error: Error, forceStack?: boolean): string | TimeoutError | undefined;
|
|
550
720
|
protected _canRequestBeRetried(request: Request, error: Error): boolean;
|
|
551
721
|
/**
|
|
552
|
-
* Updates handledRequestsCount from possibly stored counts,
|
|
553
|
-
* usually after worker migration. Since one of the stores
|
|
554
|
-
* needs to have priority when both are present,
|
|
555
|
-
* it is the request queue, because generally, the request
|
|
556
|
-
* list will first be dumped into the queue and then left
|
|
557
|
-
* empty.
|
|
722
|
+
* Updates handledRequestsCount from possibly stored counts, usually after worker migration.
|
|
558
723
|
*/
|
|
559
724
|
protected _loadHandledRequestCount(): Promise<void>;
|
|
560
725
|
protected _executeHooks<HookLike extends (...args: any[]) => Awaitable<void>>(hooks: HookLike[], ...args: Parameters<HookLike>): Promise<void>;
|
|
561
726
|
/**
|
|
562
|
-
*
|
|
563
|
-
*
|
|
727
|
+
* Stops the crawler immediately.
|
|
728
|
+
*
|
|
729
|
+
* This method doesn't wait for currently active requests to finish.
|
|
730
|
+
*
|
|
731
|
+
* To stop the crawler gracefully (waiting for all running requests to finish), use {@link BasicCrawler.stop|`crawler.stop()`} instead.
|
|
564
732
|
*/
|
|
565
733
|
teardown(): Promise<void>;
|
|
566
734
|
protected _getCookieHeaderFromRequest(request: Request): string;
|
|
567
735
|
private _getRequestQueue;
|
|
568
|
-
|
|
736
|
+
private requestMatchesEnqueueStrategy;
|
|
569
737
|
}
|
|
570
738
|
export interface CreateContextOptions {
|
|
571
739
|
request: Request;
|
|
572
|
-
session
|
|
740
|
+
session: Session;
|
|
573
741
|
proxyInfo?: ProxyInfo;
|
|
574
742
|
}
|
|
575
743
|
export interface CrawlerAddRequestsOptions extends AddRequestsBatchedOptions {
|