@crawlee/basic 4.0.0-beta.19 → 4.0.0-beta.191
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 +14 -14
- package/index.d.ts +11 -2
- package/index.js +11 -1
- package/internals/autoscaling/autoscaled_pool.d.ts +198 -0
- package/internals/autoscaling/autoscaled_pool.js +388 -0
- package/internals/autoscaling/concurrency_system.d.ts +275 -0
- package/internals/autoscaling/concurrency_system.js +365 -0
- package/internals/autoscaling/cpu_load_signal.d.ts +43 -0
- package/internals/autoscaling/cpu_load_signal.js +46 -0
- package/internals/autoscaling/event_loop_load_signal.d.ts +51 -0
- package/internals/autoscaling/event_loop_load_signal.js +60 -0
- package/internals/autoscaling/index.d.ts +9 -0
- package/internals/autoscaling/index.js +9 -0
- package/internals/autoscaling/load_signal.d.ts +98 -0
- package/internals/autoscaling/load_signal.js +103 -0
- package/internals/autoscaling/memory_load_signal.d.ts +47 -0
- package/internals/autoscaling/memory_load_signal.js +104 -0
- package/internals/autoscaling/snapshotter.d.ts +84 -0
- package/internals/autoscaling/snapshotter.js +67 -0
- package/internals/autoscaling/storage_backend_load_signal.d.ts +56 -0
- package/internals/autoscaling/storage_backend_load_signal.js +73 -0
- package/internals/autoscaling/system_status.d.ts +122 -0
- package/internals/autoscaling/system_status.js +139 -0
- package/internals/autoscaling/weighted_avg.d.ts +5 -0
- package/internals/autoscaling/weighted_avg.js +14 -0
- package/internals/basic-crawler.d.ts +465 -335
- package/internals/basic-crawler.js +1402 -820
- package/internals/cookie_utils.d.ts +44 -0
- package/internals/cookie_utils.js +122 -0
- package/internals/crawler-run.d.ts +76 -0
- package/internals/crawler-run.js +142 -0
- package/internals/crawlers/context_pipeline.d.ts +71 -0
- package/internals/crawlers/context_pipeline.js +117 -0
- package/internals/crawlers/crawler_commons.d.ts +194 -0
- package/internals/crawlers/crawler_commons.js +1 -0
- package/internals/crawlers/error_snapshotter.d.ts +57 -0
- package/internals/crawlers/error_snapshotter.js +117 -0
- package/internals/crawlers/error_tracker.d.ts +54 -0
- package/internals/crawlers/error_tracker.js +308 -0
- package/internals/crawlers/index.d.ts +5 -0
- package/internals/crawlers/index.js +4 -0
- package/internals/crawlers/internals/types.d.ts +7 -0
- package/internals/crawlers/internals/types.js +1 -0
- package/internals/crawlers/statistics.d.ts +318 -0
- package/internals/crawlers/statistics.js +525 -0
- package/internals/crawling_request.d.ts +86 -0
- package/internals/crawling_request.js +127 -0
- package/internals/enqueue_links/enqueue_links.d.ts +152 -0
- package/internals/enqueue_links/enqueue_links.js +76 -0
- package/internals/enqueue_links/index.d.ts +2 -0
- package/internals/enqueue_links/index.js +2 -0
- package/internals/enqueue_links/shared.d.ts +99 -0
- package/internals/enqueue_links/shared.js +258 -0
- package/internals/errors.d.ts +55 -0
- package/internals/errors.js +67 -0
- package/internals/http.d.ts +9 -0
- package/internals/http.js +28 -0
- package/internals/request-timeout.d.ts +48 -0
- package/internals/request-timeout.js +73 -0
- package/internals/router.d.ts +306 -0
- package/internals/router.js +310 -0
- package/internals/send-request.d.ts +4 -4
- package/internals/send-request.js +22 -11
- package/internals/session_pool/consts.d.ts +3 -0
- package/internals/session_pool/consts.js +3 -0
- package/internals/session_pool/errors.d.ts +7 -0
- package/internals/session_pool/errors.js +11 -0
- package/internals/session_pool/fingerprint.d.ts +9 -0
- package/internals/session_pool/fingerprint.js +30 -0
- package/internals/session_pool/index.d.ts +4 -0
- package/internals/session_pool/index.js +4 -0
- package/internals/session_pool/session.d.ts +153 -0
- package/internals/session_pool/session.js +221 -0
- package/internals/session_pool/session_pool.d.ts +242 -0
- package/internals/session_pool/session_pool.js +429 -0
- package/internals/sitemap_request_loader.d.ts +196 -0
- package/internals/sitemap_request_loader.js +432 -0
- package/internals/throttling_request_manager.d.ts +214 -0
- package/internals/throttling_request_manager.js +825 -0
- package/package.json +19 -13
- package/index.d.ts.map +0 -1
- package/index.js.map +0 -1
- package/internals/basic-crawler.d.ts.map +0 -1
- package/internals/basic-crawler.js.map +0 -1
- package/internals/send-request.d.ts.map +0 -1
- package/internals/send-request.js.map +0 -1
|
@@ -1,25 +1,45 @@
|
|
|
1
|
-
import type { AddRequestsBatchedOptions, AddRequestsBatchedResult,
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
1
|
+
import type { AddRequestsBatchedOptions, AddRequestsBatchedResult, CrawleeLogger, DatasetExportOptions, IProxyConfiguration, IRequestLoader, IRequestManager, RequestsLike, Source, StorageIdentifier, StorageWritePolicy } from '@crawlee/core';
|
|
2
|
+
import { Configuration, Request, Dataset, EventManager, RequestQueue } from '@crawlee/core';
|
|
3
|
+
import { BaseHttpClient } from '@crawlee/http-client';
|
|
4
|
+
import type { Awaitable, Dictionary, ISession, ISessionPool, ProxyInfo, SetStatusMessageOptions, StorageBackend } from '@crawlee/types';
|
|
4
5
|
import { RobotsTxtFile } from '@crawlee/utils';
|
|
5
|
-
import type { ReadonlyDeep
|
|
6
|
-
import
|
|
6
|
+
import type { ReadonlyDeep } from 'type-fest';
|
|
7
|
+
import { z } from 'zod';
|
|
7
8
|
import { TimeoutError } from '@apify/timeout';
|
|
9
|
+
import type { TaskLoopOptions } from './autoscaling/autoscaled_pool.js';
|
|
10
|
+
import type { ConcurrencySystemOptions, IConcurrencySystem } from './autoscaling/concurrency_system.js';
|
|
11
|
+
import { ConcurrencySystem } from './autoscaling/concurrency_system.js';
|
|
12
|
+
import type { FinalStatistics } from './autoscaling/system_status.js';
|
|
13
|
+
import { ContextPipeline } from './crawlers/context_pipeline.js';
|
|
14
|
+
import type { CrawlingContext, TypedRequestsLike } from './crawlers/crawler_commons.js';
|
|
15
|
+
import { CrawlingRequest } from './crawling_request.js';
|
|
16
|
+
import type { IStatistics, StatisticState } from './crawlers/statistics.js';
|
|
17
|
+
import type { EnqueueUrlsOptions, SkippedRequestCallback } from './enqueue_links/index.js';
|
|
18
|
+
import type { GetUserDataFromRequest, RouterHandler, RouterRoutes } from './router.js';
|
|
8
19
|
export interface BasicCrawlingContext<UserData extends Dictionary = Dictionary> extends CrawlingContext<UserData> {
|
|
9
20
|
}
|
|
21
|
+
export { navigationDeadlineKey, remainingNavigationWindowMillis } from './request-timeout.js';
|
|
10
22
|
export type RequestHandler<Context extends CrawlingContext = CrawlingContext> = (inputs: Context) => Awaitable<void>;
|
|
11
|
-
|
|
12
|
-
|
|
23
|
+
/**
|
|
24
|
+
* An error handler receives the crawling context and the error that was thrown while processing the request.
|
|
25
|
+
*
|
|
26
|
+
* Unlike the {@link RequestHandler}, an error handler may run before the context pipeline has finished
|
|
27
|
+
* building the full context (e.g. when navigation or session setup fails). Therefore only `BaseContext` is
|
|
28
|
+
* guaranteed to be present, while the extra properties added by the pipeline and `extendContext` (the
|
|
29
|
+
* difference between `BaseContext` and `ExtendedContext`) are only available as a `Partial`.
|
|
30
|
+
*/
|
|
31
|
+
export type ErrorHandler<BaseContext extends CrawlingContext = CrawlingContext, ExtendedContext extends BaseContext = BaseContext> = (inputs: BaseContext & Partial<ExtendedContext>, error: Error) => Awaitable<void>;
|
|
32
|
+
export interface StatusMessageCallbackParams<Context extends CrawlingContext = BasicCrawlingContext, Crawler extends BasicCrawler<any, any, any, any> = BasicCrawler<Context>> {
|
|
13
33
|
state: StatisticState;
|
|
14
34
|
crawler: Crawler;
|
|
15
35
|
previousState: StatisticState;
|
|
16
36
|
message: string;
|
|
17
37
|
}
|
|
18
|
-
export type StatusMessageCallback<Context extends CrawlingContext = BasicCrawlingContext, Crawler extends BasicCrawler<any> = BasicCrawler<Context>> = (params: StatusMessageCallbackParams<Context, Crawler>) => Awaitable<void>;
|
|
38
|
+
export type StatusMessageCallback<Context extends CrawlingContext = BasicCrawlingContext, Crawler extends BasicCrawler<any, any, any, any> = BasicCrawler<Context>> = (params: StatusMessageCallbackParams<Context, Crawler>) => Awaitable<void>;
|
|
19
39
|
export type RequireContextPipeline<DefaultContextType extends CrawlingContext, FinalContextType extends DefaultContextType> = DefaultContextType extends FinalContextType ? {} : {
|
|
20
40
|
contextPipelineBuilder: () => ContextPipeline<CrawlingContext, FinalContextType>;
|
|
21
41
|
};
|
|
22
|
-
export interface BasicCrawlerOptions<Context extends CrawlingContext = CrawlingContext, ContextExtension = Dictionary<never>, ExtendedContext extends Context = Context & ContextExtension> {
|
|
42
|
+
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 = {}> {
|
|
23
43
|
/**
|
|
24
44
|
* User-provided function that performs the logic of the crawler. It is called for each URL to crawl.
|
|
25
45
|
*
|
|
@@ -35,11 +55,17 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = CrawlingC
|
|
|
35
55
|
* To make this work, we should **always**
|
|
36
56
|
* let our function throw exceptions rather than catch them.
|
|
37
57
|
* The exceptions are logged to the request using the
|
|
38
|
-
* {@link
|
|
58
|
+
* {@link CrawlingRequest.pushErrorMessage|`request.pushErrorMessage()`} function.
|
|
39
59
|
*/
|
|
40
|
-
requestHandler?: RequestHandler<ExtendedContext>;
|
|
60
|
+
requestHandler?: RouterHandler<ExtendedContext, Routes> | RequestHandler<ExtendedContext>;
|
|
41
61
|
/**
|
|
42
|
-
* Allows the user to extend the crawling context
|
|
62
|
+
* Allows the user to extend the crawling context with custom functionality (helpers, references, etc.).
|
|
63
|
+
*
|
|
64
|
+
* `extendContext` runs *before* navigation, so the returned members are visible to the
|
|
65
|
+
* `preNavigationHooks`, `postNavigationHooks`, and the `requestHandler` alike. As a consequence,
|
|
66
|
+
* the `context` passed to `extendContext` is the pre-navigation {@link CrawlingContext} and does
|
|
67
|
+
* **not** include navigation-dependent members (e.g. `page`, `response`, `$`, `body`). If you need
|
|
68
|
+
* those, use a `postNavigationHook` or the `requestHandler` instead.
|
|
43
69
|
*
|
|
44
70
|
* **Example usage:**
|
|
45
71
|
*
|
|
@@ -59,7 +85,7 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = CrawlingC
|
|
|
59
85
|
* });
|
|
60
86
|
* ```
|
|
61
87
|
*/
|
|
62
|
-
extendContext?: (context:
|
|
88
|
+
extendContext?: (context: CrawlingContext) => Awaitable<ContextExtension>;
|
|
63
89
|
/**
|
|
64
90
|
* *Intended for BasicCrawler subclasses*. Prepares a context pipeline that transforms the initial crawling context into the shape given by the `Context` type parameter.
|
|
65
91
|
*
|
|
@@ -68,23 +94,25 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = CrawlingC
|
|
|
68
94
|
contextPipelineBuilder?: () => ContextPipeline<CrawlingContext, Context>;
|
|
69
95
|
/**
|
|
70
96
|
* Static list of URLs to be processed.
|
|
71
|
-
*
|
|
72
|
-
*
|
|
73
|
-
*
|
|
97
|
+
*
|
|
98
|
+
* @deprecated Use the `requestManager` option instead. To combine a read-only loader (such as a `RequestList`)
|
|
99
|
+
* with a writable queue, build a tandem with {@link IRequestLoader.toTandem|`requestList.toTandem(requestQueue)`}
|
|
100
|
+
* and pass the result as `requestManager`. When both `requestList` and `requestQueue` are provided, they are
|
|
101
|
+
* combined into a tandem automatically.
|
|
74
102
|
*/
|
|
75
|
-
requestList?:
|
|
103
|
+
requestList?: IRequestLoader;
|
|
76
104
|
/**
|
|
77
105
|
* Dynamic queue of URLs to be processed. This is useful for recursive crawling of websites.
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
* it
|
|
106
|
+
*
|
|
107
|
+
* @deprecated Use the `requestManager` option instead. A `RequestQueue` is itself a request manager, so you can
|
|
108
|
+
* pass it directly as `requestManager`.
|
|
81
109
|
*/
|
|
82
|
-
requestQueue?:
|
|
110
|
+
requestQueue?: RequestQueue;
|
|
83
111
|
/**
|
|
84
|
-
*
|
|
112
|
+
* Manager of requests that should be processed by the crawler. Mutually exclusive with the deprecated
|
|
113
|
+
* `requestQueue` and `requestList` options.
|
|
85
114
|
*
|
|
86
|
-
*
|
|
87
|
-
* If using this, the type of `BasicCrawler.requestQueue` may not be fully compatible with the `RequestProvider` class.
|
|
115
|
+
* If not provided, the crawler will open the default {@link RequestQueue} when it is first needed.
|
|
88
116
|
*/
|
|
89
117
|
requestManager?: IRequestManager;
|
|
90
118
|
/**
|
|
@@ -113,27 +141,21 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = CrawlingC
|
|
|
113
141
|
failedRequestHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;
|
|
114
142
|
/**
|
|
115
143
|
* Specifies the maximum number of retries allowed for a request if its processing fails.
|
|
116
|
-
* This includes retries due to navigation errors or errors thrown from user-supplied
|
|
117
|
-
* (`requestHandler`, `preNavigationHooks`, `postNavigationHooks`).
|
|
118
|
-
*
|
|
119
|
-
* This limit does not apply to retries triggered by session rotation
|
|
120
|
-
* (see {@link BasicCrawlerOptions.maxSessionRotations|`maxSessionRotations`}).
|
|
144
|
+
* This includes retries due to navigation errors, session/proxy errors, or errors thrown from user-supplied
|
|
145
|
+
* functions (`requestHandler`, `preNavigationHooks`, `postNavigationHooks`).
|
|
121
146
|
* @default 3
|
|
122
147
|
*/
|
|
123
148
|
maxRequestRetries?: number;
|
|
124
149
|
/**
|
|
125
|
-
* Indicates how much time (in seconds) to wait before crawling another same domain request.
|
|
150
|
+
* Indicates how much time (in seconds) to wait before crawling another same domain request. Subdomains are
|
|
151
|
+
* paced together with the site they belong to.
|
|
152
|
+
*
|
|
153
|
+
* Offered to the crawler's request manager as a `minIntervalEverywhere` {@link PacingSignal}; a manager that
|
|
154
|
+
* already paces every domain it dispatches to takes it, so no domain ends up with two clocks. Otherwise the
|
|
155
|
+
* crawler wraps its request manager in a {@link ThrottlingRequestManager} of its own.
|
|
126
156
|
* @default 0
|
|
127
157
|
*/
|
|
128
158
|
sameDomainDelaySecs?: number;
|
|
129
|
-
/**
|
|
130
|
-
* Maximum number of session rotations per request.
|
|
131
|
-
* The crawler will automatically rotate the session in case of a proxy error or if it gets blocked by the website.
|
|
132
|
-
*
|
|
133
|
-
* The session rotations are not counted towards the {@link BasicCrawlerOptions.maxRequestRetries|`maxRequestRetries`} limit.
|
|
134
|
-
* @default 10
|
|
135
|
-
*/
|
|
136
|
-
maxSessionRotations?: number;
|
|
137
159
|
/**
|
|
138
160
|
* Maximum number of pages that the crawler will open. The crawl will stop when this limit is reached.
|
|
139
161
|
* This value should always be set in order to prevent infinite loops in misconfigured crawlers.
|
|
@@ -147,29 +169,56 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = CrawlingC
|
|
|
147
169
|
*/
|
|
148
170
|
maxCrawlDepth?: number;
|
|
149
171
|
/**
|
|
150
|
-
*
|
|
151
|
-
*
|
|
152
|
-
*
|
|
153
|
-
*
|
|
154
|
-
*
|
|
172
|
+
* Lets you override the predicates that steer the crawler's task loop: `isTaskReadyFunction` (may another request
|
|
173
|
+
* start?) and `isFinishedFunction` (is the crawl over?). The task itself — fetching a request and running it
|
|
174
|
+
* through the pipeline — is owned by the crawler and cannot be overridden.
|
|
175
|
+
*
|
|
176
|
+
* Concurrency is configured elsewhere — through the `minConcurrency`/`maxConcurrency`/`maxRequestsPerMinute`
|
|
177
|
+
* shortcuts, or a {@link BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} for finer control.
|
|
155
178
|
*/
|
|
156
|
-
|
|
179
|
+
taskLoopOptions?: TaskLoopOptions;
|
|
180
|
+
/**
|
|
181
|
+
* A pre-configured concurrency governor — the component that decides whether there is free compute for one more
|
|
182
|
+
* task. Typically a {@link ConcurrencySystem}, though any {@link IConcurrencySystem} is accepted. All
|
|
183
|
+
* scaling configuration (min/max/desired concurrency, scaling ratios, `maxTasksPerMinute`, snapshotter tuning)
|
|
184
|
+
* lives on the instance itself.
|
|
185
|
+
*
|
|
186
|
+
* Inject the *same* instance into several concurrent crawlers to cap their **combined** concurrency against a
|
|
187
|
+
* single budget. Each crawler still builds and drives its own {@link AutoscaledPool}; only the load/scaling
|
|
188
|
+
* accounting is shared.
|
|
189
|
+
*
|
|
190
|
+
* Mutually exclusive with the `minConcurrency`/`maxConcurrency`/`initialConcurrency`/`maxRequestsPerMinute`
|
|
191
|
+
* shortcuts, which configure the default system this one replaces — combining the two throws.
|
|
192
|
+
*
|
|
193
|
+
* You own a supplied system's lifecycle: `start()` it before `run()` (which throws otherwise) and `stop()` it once
|
|
194
|
+
* every crawler borrowing it has finished. The crawler does neither on your behalf.
|
|
195
|
+
*/
|
|
196
|
+
concurrencySystem?: IConcurrencySystem;
|
|
157
197
|
/**
|
|
158
198
|
* Sets the minimum concurrency (parallelism) for the crawl. Shortcut for the
|
|
159
|
-
*
|
|
199
|
+
* {@link ConcurrencySystemOptions.minConcurrency|`minConcurrency`} option of the crawler's default
|
|
200
|
+
* {@link ConcurrencySystem}.
|
|
160
201
|
* > *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.
|
|
161
202
|
* If not sure, it's better to keep the default value and the concurrency will scale up automatically.
|
|
162
203
|
*/
|
|
163
204
|
minConcurrency?: number;
|
|
164
205
|
/**
|
|
165
206
|
* Sets the maximum concurrency (parallelism) for the crawl. Shortcut for the
|
|
166
|
-
*
|
|
207
|
+
* {@link ConcurrencySystemOptions.maxConcurrency|`maxConcurrency`} option of the crawler's default
|
|
208
|
+
* {@link ConcurrencySystem}.
|
|
167
209
|
*/
|
|
168
210
|
maxConcurrency?: number;
|
|
211
|
+
/**
|
|
212
|
+
* Sets the concurrency (parallelism) the crawl starts with, before any scaling happens. Shortcut for the
|
|
213
|
+
* {@link ConcurrencySystemOptions.desiredConcurrency|`desiredConcurrency`} option of the crawler's default
|
|
214
|
+
* {@link ConcurrencySystem}. Defaults to `minConcurrency`.
|
|
215
|
+
*/
|
|
216
|
+
initialConcurrency?: number;
|
|
169
217
|
/**
|
|
170
218
|
* The maximum number of requests per minute the crawler should run.
|
|
171
219
|
* By default, this is set to `Infinity`, but we can pass any positive, non-zero integer.
|
|
172
|
-
* Shortcut for the
|
|
220
|
+
* Shortcut for the {@link ConcurrencySystemOptions.maxTasksPerMinute|`maxTasksPerMinute`} option of the
|
|
221
|
+
* crawler's default {@link ConcurrencySystem}.
|
|
173
222
|
*/
|
|
174
223
|
maxRequestsPerMinute?: number;
|
|
175
224
|
/**
|
|
@@ -179,14 +228,14 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = CrawlingC
|
|
|
179
228
|
*/
|
|
180
229
|
keepAlive?: boolean;
|
|
181
230
|
/**
|
|
182
|
-
*
|
|
183
|
-
*
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
*
|
|
231
|
+
* An existing session pool instance to use. When provided, the crawler will use this pool directly instead of
|
|
232
|
+
* creating a new one, enabling session sharing across multiple crawlers. The crawler will not tear down a shared
|
|
233
|
+
* pool — the caller is responsible for its lifecycle.
|
|
234
|
+
*
|
|
235
|
+
* Accepts the built-in {@link SessionPool} or any object implementing the {@link ISessionPool} interface,
|
|
236
|
+
* so custom session-management strategies can be plugged in.
|
|
188
237
|
*/
|
|
189
|
-
|
|
238
|
+
sessionPool?: ISessionPool;
|
|
190
239
|
/**
|
|
191
240
|
* Defines the length of the interval for calling the `setStatusMessage` in seconds.
|
|
192
241
|
*/
|
|
@@ -208,6 +257,15 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = CrawlingC
|
|
|
208
257
|
* ```
|
|
209
258
|
*/
|
|
210
259
|
statusMessageCallback?: StatusMessageCallback;
|
|
260
|
+
/**
|
|
261
|
+
* HTTP status codes that indicate the session should be retired.
|
|
262
|
+
*
|
|
263
|
+
* A 429 from a domain covered by a {@link ThrottlingRequestManager} is handled as a rate limit before
|
|
264
|
+
* this is consulted, so removing 429 here only affects domains that manager does not cover.
|
|
265
|
+
*
|
|
266
|
+
* @default [401, 403, 429]
|
|
267
|
+
*/
|
|
268
|
+
blockedStatusCodes?: number[];
|
|
211
269
|
/**
|
|
212
270
|
* If set to `true`, the crawler will automatically try to bypass any detected bot protection.
|
|
213
271
|
*
|
|
@@ -235,256 +293,251 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = CrawlingC
|
|
|
235
293
|
* 4. or because the {@link BasicCrawlerOptions.maxRequestsPerCrawl|`maxRequestsPerCrawl`} limit has been reached
|
|
236
294
|
*/
|
|
237
295
|
onSkippedRequest?: SkippedRequestCallback;
|
|
238
|
-
/** @internal */
|
|
239
|
-
log?: Log;
|
|
240
|
-
/**
|
|
241
|
-
* Enables experimental features of Crawlee, which can alter the behavior of the crawler.
|
|
242
|
-
* WARNING: these options are not guaranteed to be stable and may change or be removed at any time.
|
|
243
|
-
*/
|
|
244
|
-
experiments?: CrawlerExperiments;
|
|
245
296
|
/**
|
|
246
|
-
*
|
|
247
|
-
*
|
|
297
|
+
* A preconfigured statistics instance. When provided, the crawler records into it instead of building its own and
|
|
298
|
+
* will not `reset()` it between `run()` calls. Accepts the built-in {@link Statistics} or any object
|
|
299
|
+
* implementing {@link IStatistics}.
|
|
300
|
+
*
|
|
301
|
+
* Custom fields declared via {@link StatisticsOptions.stateExtension|`stateExtension`} are carried over to
|
|
302
|
+
* {@link BasicCrawler.statistics|`crawler.statistics.state`}:
|
|
303
|
+
*
|
|
304
|
+
* ```ts
|
|
305
|
+
* const statistics = new Statistics({ stateExtension: { defaultState: { productsFound: 0 } } });
|
|
306
|
+
*
|
|
307
|
+
* const crawler = new BasicCrawler({
|
|
308
|
+
* statistics,
|
|
309
|
+
* requestHandler: async () => {
|
|
310
|
+
* statistics.state.productsFound++;
|
|
311
|
+
* },
|
|
312
|
+
* });
|
|
313
|
+
*
|
|
314
|
+
* await crawler.run();
|
|
315
|
+
* // the custom fields are typed on `crawler.statistics` too
|
|
316
|
+
* console.log(crawler.statistics.state.productsFound);
|
|
317
|
+
* ```
|
|
248
318
|
*/
|
|
249
|
-
|
|
319
|
+
statistics?: IStatistics<StatisticStateExtension>;
|
|
250
320
|
/**
|
|
251
321
|
* HTTP client implementation for the `sendRequest` context helper and for plain HTTP crawling.
|
|
252
|
-
* Defaults to
|
|
322
|
+
* Defaults to {@link ImpitHttpClient} when `@crawlee/impit-client` is installed, otherwise {@link FetchHttpClient}.
|
|
253
323
|
*/
|
|
254
324
|
httpClient?: BaseHttpClient;
|
|
255
325
|
/**
|
|
256
326
|
* If set, the crawler will be configured for all connections to use
|
|
257
327
|
* the Proxy URLs provided and rotated according to the configuration.
|
|
258
328
|
*/
|
|
259
|
-
proxyConfiguration?:
|
|
260
|
-
}
|
|
261
|
-
/**
|
|
262
|
-
* A set of options that you can toggle to enable experimental features in Crawlee.
|
|
263
|
-
*
|
|
264
|
-
* NOTE: These options will not respect semantic versioning and may be removed or changed at any time. Use at your own risk.
|
|
265
|
-
* If you do use these and encounter issues, please report them to us.
|
|
266
|
-
*/
|
|
267
|
-
export interface CrawlerExperiments {
|
|
329
|
+
proxyConfiguration?: IProxyConfiguration;
|
|
268
330
|
/**
|
|
269
|
-
*
|
|
270
|
-
* If
|
|
271
|
-
* - report it to us: https://github.com/apify/crawlee
|
|
272
|
-
* - set `requestLocking` to `false` in the `experiments` option of the crawler
|
|
331
|
+
* Custom configuration to use for this crawler.
|
|
332
|
+
* If provided, the crawler will use its own ServiceLocator instance instead of the global one.
|
|
273
333
|
*/
|
|
274
|
-
|
|
275
|
-
}
|
|
276
|
-
/**
|
|
277
|
-
* Provides a simple framework for parallel crawling of web pages.
|
|
278
|
-
* The URLs to crawl are fed either from a static list of URLs
|
|
279
|
-
* or from a dynamic queue of URLs enabling recursive crawling of websites.
|
|
280
|
-
*
|
|
281
|
-
* `BasicCrawler` is a low-level tool that requires the user to implement the page
|
|
282
|
-
* download and data extraction functionality themselves.
|
|
283
|
-
* If we want a crawler that already facilitates this functionality,
|
|
284
|
-
* we should consider using {@link CheerioCrawler}, {@link PuppeteerCrawler} or {@link PlaywrightCrawler}.
|
|
285
|
-
*
|
|
286
|
-
* `BasicCrawler` invokes the user-provided {@link BasicCrawlerOptions.requestHandler|`requestHandler`}
|
|
287
|
-
* for each {@link Request} object, which represents a single URL to crawl.
|
|
288
|
-
* The {@link Request} objects are fed from the {@link RequestList} or {@link RequestQueue}
|
|
289
|
-
* instances provided by the {@link BasicCrawlerOptions.requestList|`requestList`} or {@link BasicCrawlerOptions.requestQueue|`requestQueue`}
|
|
290
|
-
* constructor options, respectively. If neither `requestList` nor `requestQueue` options are provided,
|
|
291
|
-
* the crawler will open the default request queue either when the {@link BasicCrawler.addRequests|`crawler.addRequests()`} function is called,
|
|
292
|
-
* or if `requests` parameter (representing the initial requests) of the {@link BasicCrawler.run|`crawler.run()`} function is provided.
|
|
293
|
-
*
|
|
294
|
-
* If both {@link BasicCrawlerOptions.requestList|`requestList`} and {@link BasicCrawlerOptions.requestQueue|`requestQueue`} options are used,
|
|
295
|
-
* the instance first processes URLs from the {@link RequestList} and automatically enqueues all of them
|
|
296
|
-
* to the {@link RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.
|
|
297
|
-
*
|
|
298
|
-
* The crawler finishes if there are no more {@link Request} objects to crawl.
|
|
299
|
-
*
|
|
300
|
-
* New requests are only dispatched when there is enough free CPU and memory available,
|
|
301
|
-
* using the functionality provided by the {@link AutoscaledPool} class.
|
|
302
|
-
* All {@link AutoscaledPool} configuration options can be passed to the {@link BasicCrawlerOptions.autoscaledPoolOptions|`autoscaledPoolOptions`}
|
|
303
|
-
* parameter of the `BasicCrawler` constructor.
|
|
304
|
-
* For user convenience, the {@link AutoscaledPoolOptions.minConcurrency|`minConcurrency`} and
|
|
305
|
-
* {@link AutoscaledPoolOptions.maxConcurrency|`maxConcurrency`} options of the
|
|
306
|
-
* underlying {@link AutoscaledPool} constructor are available directly in the `BasicCrawler` constructor.
|
|
307
|
-
*
|
|
308
|
-
* **Example usage:**
|
|
309
|
-
*
|
|
310
|
-
* ```javascript
|
|
311
|
-
* import { BasicCrawler, Dataset } from 'crawlee';
|
|
312
|
-
*
|
|
313
|
-
* // Create a crawler instance
|
|
314
|
-
* const crawler = new BasicCrawler({
|
|
315
|
-
* async requestHandler({ request, sendRequest }) {
|
|
316
|
-
* // 'request' contains an instance of the Request class
|
|
317
|
-
* // Here we simply fetch the HTML of the page and store it to a dataset
|
|
318
|
-
* const { body } = await sendRequest({
|
|
319
|
-
* url: request.url,
|
|
320
|
-
* method: request.method,
|
|
321
|
-
* body: request.payload,
|
|
322
|
-
* headers: request.headers,
|
|
323
|
-
* });
|
|
324
|
-
*
|
|
325
|
-
* await Dataset.pushData({
|
|
326
|
-
* url: request.url,
|
|
327
|
-
* html: body,
|
|
328
|
-
* })
|
|
329
|
-
* },
|
|
330
|
-
* });
|
|
331
|
-
*
|
|
332
|
-
* // Enqueue the initial requests and run the crawler
|
|
333
|
-
* await crawler.run([
|
|
334
|
-
* 'http://www.example.com/page-1',
|
|
335
|
-
* 'http://www.example.com/page-2',
|
|
336
|
-
* ]);
|
|
337
|
-
* ```
|
|
338
|
-
* @category Crawlers
|
|
339
|
-
*/
|
|
340
|
-
export declare class BasicCrawler<Context extends CrawlingContext = CrawlingContext, ContextExtension = Dictionary<never>, ExtendedContext extends Context = Context & ContextExtension> {
|
|
341
|
-
readonly config: Configuration;
|
|
342
|
-
protected static readonly CRAWLEE_STATE_KEY = "CRAWLEE_STATE";
|
|
334
|
+
configuration?: Configuration;
|
|
343
335
|
/**
|
|
344
|
-
*
|
|
336
|
+
* Custom storage backend to use for this crawler.
|
|
337
|
+
* If provided, the crawler will use its own ServiceLocator instance instead of the global one.
|
|
345
338
|
*/
|
|
346
|
-
|
|
339
|
+
storageBackend?: StorageBackend;
|
|
347
340
|
/**
|
|
348
|
-
*
|
|
349
|
-
*
|
|
341
|
+
* Custom event manager to use for this crawler.
|
|
342
|
+
* If provided, the crawler will use its own ServiceLocator instance instead of the global one.
|
|
350
343
|
*/
|
|
351
|
-
|
|
344
|
+
eventManager?: EventManager;
|
|
352
345
|
/**
|
|
353
|
-
*
|
|
354
|
-
*
|
|
355
|
-
* Only available if used by the crawler.
|
|
346
|
+
* Custom logger to use for this crawler.
|
|
347
|
+
* If provided, the crawler will use its own ServiceLocator instance instead of the global one.
|
|
356
348
|
*/
|
|
357
|
-
|
|
349
|
+
logger?: CrawleeLogger;
|
|
358
350
|
/**
|
|
359
|
-
*
|
|
351
|
+
* A unique identifier for the crawler instance. This ID is used to isolate the state returned by
|
|
352
|
+
* {@link BasicCrawler.useState|`crawler.useState()`} from other crawler instances.
|
|
353
|
+
*
|
|
354
|
+
* When multiple crawler instances use `useState()` without an explicit `id`, they will share the same
|
|
355
|
+
* state object for backward compatibility. A warning will be logged in this case.
|
|
356
|
+
*
|
|
357
|
+
* To ensure each crawler has its own isolated state that also persists across script restarts
|
|
358
|
+
* (e.g., during Apify migrations), provide a stable, unique ID for each crawler instance.
|
|
359
|
+
*
|
|
360
|
+
*/
|
|
361
|
+
id?: string;
|
|
362
|
+
/**
|
|
363
|
+
* Makes the storage writes performed while handling a request atomic with respect to the request
|
|
364
|
+
* succeeding: they are recorded in a {@link StorageTransaction} spanning the whole request
|
|
365
|
+
* lifecycle and only applied when the request handler succeeds, so a thrown handler leaves no partial
|
|
366
|
+
* writes behind and a retry does not double-write. Reads within the handler see its own writes.
|
|
367
|
+
*
|
|
368
|
+
* `false` disables the mechanism entirely; an object overrides the per-storage-type
|
|
369
|
+
* {@link StorageWritePolicy} (e.g. `{ requestQueue: 'deferred' }` for all-or-nothing enqueues).
|
|
370
|
+
* {@link withDirectStorageAccess} is the per-call-site escape hatch; `useState()` is deliberately
|
|
371
|
+
* *not* transactional.
|
|
372
|
+
*
|
|
373
|
+
* @default true
|
|
374
|
+
*/
|
|
375
|
+
transactionalStorage?: boolean | Partial<StorageWritePolicy>;
|
|
376
|
+
/**
|
|
377
|
+
* An array of HTTP response [Status Codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) to be excluded from error consideration.
|
|
378
|
+
* By default, status codes >= 500 trigger errors.
|
|
379
|
+
*/
|
|
380
|
+
ignoreHttpErrorStatusCodes?: number[];
|
|
381
|
+
/**
|
|
382
|
+
* An array of additional HTTP response [Status Codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) to be treated as errors.
|
|
383
|
+
* By default, status codes >= 500 trigger errors.
|
|
384
|
+
*/
|
|
385
|
+
additionalHttpErrorStatusCodes?: number[];
|
|
386
|
+
}
|
|
387
|
+
export declare 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 = {}> {
|
|
388
|
+
#private;
|
|
389
|
+
/**
|
|
390
|
+
* The statistics instance collecting the crawler's run statistics - either the injected `statistics` option or a
|
|
391
|
+
* crawler-built default. Typed as {@link IStatistics} so custom implementations can be plugged in.
|
|
392
|
+
*/
|
|
393
|
+
get statistics(): IStatistics<StatisticStateExtension>;
|
|
394
|
+
/**
|
|
395
|
+
* The main request-handling component of the crawler. It manages the requests that the crawler processes,
|
|
396
|
+
* combining any provided request loader and/or queue. It's initialized during the crawler startup or lazily
|
|
397
|
+
* via {@link BasicCrawler.getRequestManager|`getRequestManager()`}.
|
|
360
398
|
*/
|
|
361
399
|
protected requestManager?: IRequestManager;
|
|
362
400
|
/**
|
|
363
|
-
* A reference to the underlying
|
|
364
|
-
*
|
|
401
|
+
* A reference to the underlying session pool that manages the crawler's {@link Session|sessions}. Typed as
|
|
402
|
+
* {@link ISessionPool} so custom implementations can be plugged in via the `sessionPool` constructor option.
|
|
365
403
|
*/
|
|
366
|
-
sessionPool
|
|
404
|
+
get sessionPool(): ISessionPool;
|
|
405
|
+
/** Whether a {@link BasicCrawler.run|`run()`} is in progress on this instance. */
|
|
406
|
+
get running(): boolean;
|
|
367
407
|
/**
|
|
368
|
-
*
|
|
369
|
-
*
|
|
370
|
-
*
|
|
371
|
-
*
|
|
372
|
-
*
|
|
408
|
+
* The concurrency governor the run in progress is booking its requests against — either the
|
|
409
|
+
* {@link BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} that was injected, or the default the
|
|
410
|
+
* crawler built for itself. Read it for telemetry: `desiredConcurrency`, `currentConcurrency`, `isRunning`.
|
|
411
|
+
*
|
|
412
|
+
* > *NOTE:* `undefined` outside a run, and a crawler-owned default is rebuilt for every run — so read it
|
|
413
|
+
* during a run rather than caching it across runs.
|
|
414
|
+
*
|
|
415
|
+
* {@link IConcurrencySystem} is deliberately read-only. Tuning concurrency *while a crawl is running* means
|
|
416
|
+
* owning the instance: build a {@link ConcurrencySystem} yourself and inject it, then set
|
|
417
|
+
* `minConcurrency`/`maxConcurrency`/`desiredConcurrency` on your own reference.
|
|
373
418
|
*/
|
|
374
|
-
|
|
419
|
+
get concurrencySystem(): IConcurrencySystem | undefined;
|
|
375
420
|
/**
|
|
376
|
-
* A reference to the underlying {@link
|
|
421
|
+
* A reference to the underlying {@link IProxyConfiguration} instance that manages the crawler's proxies.
|
|
377
422
|
* Only available if used by the crawler.
|
|
378
423
|
*/
|
|
379
|
-
proxyConfiguration?:
|
|
424
|
+
readonly proxyConfiguration?: IProxyConfiguration;
|
|
380
425
|
/**
|
|
381
426
|
* Default {@link Router} instance that will be used if we don't specify any {@link BasicCrawlerOptions.requestHandler|`requestHandler`}.
|
|
382
427
|
* See {@link Router.addHandler|`router.addHandler()`} and {@link Router.addDefaultHandler|`router.addDefaultHandler()`}.
|
|
383
428
|
*/
|
|
384
|
-
readonly router: RouterHandler<Context>;
|
|
385
|
-
|
|
386
|
-
|
|
429
|
+
readonly router: RouterHandler<Context, Routes>;
|
|
430
|
+
/**
|
|
431
|
+
* The basic part of the context pipeline. Unlike the subclass pipeline, this
|
|
432
|
+
* part has no major side effects (e.g. launching a browser). It also makes typing more explicit, as subclass
|
|
433
|
+
* pipelines expect the basic crawler fields to already be present in the context at runtime.
|
|
434
|
+
*
|
|
435
|
+
* Context built with this pipeline can be passed into multiple crawler pipelines at once.
|
|
436
|
+
* This is used e.g. in the {@link AdaptivePlaywrightCrawler|`AdaptivePlaywrightCrawler`}.
|
|
437
|
+
*/
|
|
438
|
+
get basicContextPipeline(): ContextPipeline<{
|
|
439
|
+
request: CrawlingRequest;
|
|
440
|
+
}, CrawlingContext>;
|
|
387
441
|
get contextPipeline(): ContextPipeline<CrawlingContext, ExtendedContext>;
|
|
388
|
-
|
|
389
|
-
hasFinishedBefore: boolean;
|
|
390
|
-
|
|
391
|
-
protected requestHandler: RequestHandler<ExtendedContext>;
|
|
392
|
-
protected
|
|
393
|
-
|
|
394
|
-
protected
|
|
395
|
-
protected
|
|
396
|
-
protected
|
|
397
|
-
protected
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
protected maxRequestsPerCrawl?: number;
|
|
402
|
-
protected handledRequestsCount: number;
|
|
403
|
-
protected statusMessageLoggingInterval: number;
|
|
404
|
-
protected statusMessageCallback?: StatusMessageCallback;
|
|
405
|
-
protected sessionPoolOptions: SessionPoolOptions;
|
|
406
|
-
protected useSessionPool: boolean;
|
|
407
|
-
protected autoscaledPoolOptions: AutoscaledPoolOptions;
|
|
408
|
-
protected events: EventManager;
|
|
409
|
-
protected httpClient: BaseHttpClient;
|
|
410
|
-
protected retryOnBlocked: boolean;
|
|
411
|
-
protected respectRobotsTxtFile: boolean | {
|
|
412
|
-
userAgent?: string;
|
|
413
|
-
};
|
|
414
|
-
protected onSkippedRequest?: SkippedRequestCallback;
|
|
415
|
-
private _closeEvents?;
|
|
416
|
-
private shouldLogMaxProcessedRequestsExceeded;
|
|
417
|
-
private shouldLogMaxEnqueuedRequestsExceeded;
|
|
418
|
-
private experiments;
|
|
419
|
-
private readonly robotsTxtFileCache;
|
|
420
|
-
private _experimentWarnings;
|
|
442
|
+
/** Whether a `run()` on this instance has already finished - a repeated one continues where it left off. */
|
|
443
|
+
get hasFinishedBefore(): boolean;
|
|
444
|
+
get log(): CrawleeLogger;
|
|
445
|
+
protected readonly requestHandler: RequestHandler<ExtendedContext>;
|
|
446
|
+
protected readonly internalTimeoutMillis: number;
|
|
447
|
+
private get handledRequestsCount();
|
|
448
|
+
protected blockedStatusCodes: Set<number>;
|
|
449
|
+
protected readonly additionalHttpErrorStatusCodes: Set<number>;
|
|
450
|
+
protected readonly httpClient: BaseHttpClient;
|
|
451
|
+
protected readonly retryOnBlocked: boolean;
|
|
452
|
+
/**
|
|
453
|
+
* @internal
|
|
454
|
+
*/
|
|
421
455
|
protected static optionsShape: {
|
|
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
|
-
onSkippedRequest: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
|
|
466
|
-
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
467
|
-
httpClient: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
468
|
-
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
469
|
-
minConcurrency: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
|
|
470
|
-
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
471
|
-
maxConcurrency: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
|
|
472
|
-
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
473
|
-
maxRequestsPerMinute: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
|
|
474
|
-
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
475
|
-
keepAlive: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
|
|
476
|
-
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
477
|
-
log: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
478
|
-
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
479
|
-
experiments: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
480
|
-
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
481
|
-
statisticsOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
456
|
+
contextPipelineBuilder: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
|
|
457
|
+
extendContext: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
|
|
458
|
+
requestList: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
|
|
459
|
+
requestQueue: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
|
|
460
|
+
requestManager: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
|
|
461
|
+
requestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
|
|
462
|
+
requestHandlerTimeoutSecs: z.ZodOptional<z.ZodCustom<number, number>>;
|
|
463
|
+
errorHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
|
|
464
|
+
failedRequestHandler: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
|
|
465
|
+
maxRequestRetries: z.ZodDefault<z.ZodCustom<number, number>>;
|
|
466
|
+
sameDomainDelaySecs: z.ZodDefault<z.ZodCustom<number, number>>;
|
|
467
|
+
maxRequestsPerCrawl: z.ZodOptional<z.ZodCustom<number, number>>;
|
|
468
|
+
maxCrawlDepth: z.ZodOptional<z.ZodCustom<number, number>>;
|
|
469
|
+
taskLoopOptions: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
|
|
470
|
+
concurrencySystem: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
|
|
471
|
+
sessionPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
|
|
472
|
+
proxyConfiguration: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
|
|
473
|
+
statusMessageLoggingInterval: z.ZodDefault<z.ZodCustom<number, number>>;
|
|
474
|
+
statusMessageCallback: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
|
|
475
|
+
additionalHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
|
|
476
|
+
ignoreHttpErrorStatusCodes: z.ZodDefault<z.ZodArray<z.ZodCustom<number, number>>>;
|
|
477
|
+
blockedStatusCodes: z.ZodOptional<z.ZodArray<z.ZodCustom<number, number>>>;
|
|
478
|
+
retryOnBlocked: z.ZodDefault<z.ZodBoolean>;
|
|
479
|
+
respectRobotsTxtFile: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodCustom<Dictionary, Dictionary>]>>;
|
|
480
|
+
transactionalStorage: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
|
|
481
|
+
requestQueue: z.ZodOptional<z.ZodEnum<{
|
|
482
|
+
deferred: "deferred";
|
|
483
|
+
writeThrough: "writeThrough";
|
|
484
|
+
}>>;
|
|
485
|
+
}, z.core.$strict>]>>;
|
|
486
|
+
onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
|
|
487
|
+
httpClient: z.ZodOptional<z.ZodCustom<BaseHttpClient, BaseHttpClient>>;
|
|
488
|
+
configuration: z.ZodOptional<z.ZodCustom<Configuration, Configuration>>;
|
|
489
|
+
storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
|
|
490
|
+
eventManager: z.ZodOptional<z.ZodCustom<EventManager, EventManager>>;
|
|
491
|
+
logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
|
|
492
|
+
minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
|
|
493
|
+
maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
|
|
494
|
+
initialConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
|
|
495
|
+
maxRequestsPerMinute: z.ZodOptional<z.ZodCustom<number, number>>;
|
|
496
|
+
keepAlive: z.ZodOptional<z.ZodBoolean>;
|
|
497
|
+
statistics: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
|
|
498
|
+
id: z.ZodOptional<z.ZodString>;
|
|
482
499
|
};
|
|
483
500
|
/**
|
|
484
501
|
* All `BasicCrawler` parameters are passed via an options object.
|
|
485
502
|
*/
|
|
486
|
-
constructor(options?: BasicCrawlerOptions<Context, ContextExtension, ExtendedContext> & RequireContextPipeline<CrawlingContext, Context
|
|
487
|
-
|
|
503
|
+
constructor(options?: BasicCrawlerOptions<Context, ContextExtension, ExtendedContext, Routes, StatisticStateExtension> & RequireContextPipeline<CrawlingContext, Context>);
|
|
504
|
+
/**
|
|
505
|
+
* Builds the crawler-owned default {@link ConcurrencySystem} from the resolved
|
|
506
|
+
* `minConcurrency`/`maxConcurrency`/`initialConcurrency`/`maxRequestsPerMinute` shortcuts. Not called when a
|
|
507
|
+
* {@link BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} was injected.
|
|
508
|
+
*
|
|
509
|
+
* Subclasses may override this to tune the default system (e.g. {@link HttpCrawler} raises the starting
|
|
510
|
+
* concurrency and relaxes the event loop signal) while still honouring the user's shortcuts.
|
|
511
|
+
*/
|
|
512
|
+
protected createDefaultConcurrencySystem(options: ConcurrencySystemOptions): ConcurrencySystem;
|
|
513
|
+
/**
|
|
514
|
+
* Determines if the given HTTP status code is an error status code given
|
|
515
|
+
* the default behaviour and user-set preferences.
|
|
516
|
+
* @param status
|
|
517
|
+
* @returns `true` if the status code is considered an error, `false` otherwise
|
|
518
|
+
*/
|
|
519
|
+
protected isErrorStatusCode(status: number): boolean;
|
|
520
|
+
/**
|
|
521
|
+
* Builds the basic context pipeline that transforms `{ request }` into a full `CrawlingContext`.
|
|
522
|
+
* This handles base context creation, session resolution, and context helpers.
|
|
523
|
+
*/
|
|
524
|
+
private buildBasicContextPipeline;
|
|
525
|
+
private checkRobotsTxt;
|
|
526
|
+
/**
|
|
527
|
+
* Builds the subclass-specific context pipeline that transforms a `CrawlingContext` into the crawler's target context type.
|
|
528
|
+
* Subclasses should override this to add their own pipeline stages.
|
|
529
|
+
*/
|
|
530
|
+
protected buildContextPipeline(): ContextPipeline<CrawlingContext, CrawlingContext>;
|
|
531
|
+
private createBaseContext;
|
|
532
|
+
/**
|
|
533
|
+
* Fetches the next request and rebuilds it as a {@link CrawlingRequest}. A copy rather than the manager's
|
|
534
|
+
* instance: managers key on `uniqueKey`/`id`, and it is this copy that flows back into `reclaimRequest` /
|
|
535
|
+
* `markRequestAsHandled`, so nothing observes the difference.
|
|
536
|
+
*/
|
|
537
|
+
private resolveRequest;
|
|
538
|
+
private resolveSession;
|
|
539
|
+
private createContextHelpers;
|
|
540
|
+
private buildFinalContextPipeline;
|
|
488
541
|
/**
|
|
489
542
|
* Checks if the given error is a proxy error by comparing its message to a list of known proxy error messages.
|
|
490
543
|
* Used for retrying requests that failed due to proxy errors.
|
|
@@ -493,21 +546,32 @@ export declare class BasicCrawler<Context extends CrawlingContext = CrawlingCont
|
|
|
493
546
|
*/
|
|
494
547
|
protected isProxyError(error: Error): boolean;
|
|
495
548
|
/**
|
|
549
|
+
* Sets the status message for the current crawler run.
|
|
550
|
+
*
|
|
496
551
|
* This method is periodically called by the crawler, every `statusMessageLoggingInterval` seconds.
|
|
552
|
+
*
|
|
553
|
+
* The message is logged and broadcast via the {@link EventType.STATUS_MESSAGE|`statusMessage`}
|
|
554
|
+
* event. Integrations such as the Apify SDK subscribe to that event and forward the message to
|
|
555
|
+
* their status-reporting backend (e.g. the Apify platform).
|
|
497
556
|
*/
|
|
498
|
-
setStatusMessage(message: string, options?: SetStatusMessageOptions):
|
|
557
|
+
setStatusMessage(message: string, options?: SetStatusMessageOptions): void;
|
|
499
558
|
private getPeriodicLogger;
|
|
500
559
|
/**
|
|
501
|
-
* Runs the crawler. Returns a promise that resolves once
|
|
502
|
-
*
|
|
560
|
+
* Runs the crawler. Returns a promise that resolves once every request has been processed and the crawler's
|
|
561
|
+
* finished-check ({@link BasicCrawlerOptions.taskLoopOptions|`taskLoopOptions.isFinishedFunction`}, or the
|
|
562
|
+
* default "the request manager is empty") reports that the crawl is over.
|
|
503
563
|
*
|
|
504
564
|
* We can use the `requests` parameter to enqueue the initial requests — it is a shortcut for
|
|
505
565
|
* running {@link BasicCrawler.addRequests|`crawler.addRequests()`} before {@link BasicCrawler.run|`crawler.run()`}.
|
|
506
566
|
*
|
|
567
|
+
* Calling `run()` again on the same instance keeps crawling the same request manager - requests the previous
|
|
568
|
+
* run handled (a failed one counts as handled) are not processed again. Purge the queue or open a fresh one
|
|
569
|
+
* if that is what you want.
|
|
570
|
+
*
|
|
507
571
|
* @param [requests] The requests to add.
|
|
508
|
-
* @param [options] Options for the
|
|
572
|
+
* @param [options] Options for adding the initial requests.
|
|
509
573
|
*/
|
|
510
|
-
run(requests?:
|
|
574
|
+
run(requests?: TypedRequestsLike<Routes>, options?: CrawlerRunOptions): Promise<FinalStatistics>;
|
|
511
575
|
/**
|
|
512
576
|
* Gracefully stops the current run of the crawler.
|
|
513
577
|
*
|
|
@@ -515,32 +579,78 @@ export declare class BasicCrawler<Context extends CrawlingContext = CrawlingCont
|
|
|
515
579
|
*
|
|
516
580
|
* To stop the crawler immediately, use {@link BasicCrawler.teardown|`crawler.teardown()`} instead.
|
|
517
581
|
*/
|
|
518
|
-
stop(
|
|
519
|
-
|
|
582
|
+
stop(reason?: string): void;
|
|
583
|
+
/**
|
|
584
|
+
* Stops dispatching new requests, letting the in-progress ones finish. Resolves once they have settled, or rejects
|
|
585
|
+
* after `timeoutSecs` if they take too long. Unlike {@link BasicCrawler.stop|`stop()`}, this does not end the
|
|
586
|
+
* run — {@link BasicCrawler.run|`run()`} stays pending until {@link BasicCrawler.resume|`resume()`}.
|
|
587
|
+
*
|
|
588
|
+
* > *NOTE:* The {@link BasicCrawler.concurrencySystem|concurrency system} keeps monitoring and autoscaling
|
|
589
|
+
* throughout, since a shared one may still be serving other crawlers.
|
|
590
|
+
*/
|
|
591
|
+
pause(timeoutSecs?: number): Promise<void>;
|
|
592
|
+
/**
|
|
593
|
+
* Resumes a run suspended with {@link BasicCrawler.pause|`pause()`}, letting the crawler dispatch requests
|
|
594
|
+
* again. A no-op on a crawler that is not paused.
|
|
595
|
+
*/
|
|
596
|
+
resume(): void;
|
|
597
|
+
/**
|
|
598
|
+
* Returns the crawler's {@link IRequestManager|request manager}, opening the default {@link RequestQueue}
|
|
599
|
+
* if none has been configured or opened yet.
|
|
600
|
+
*/
|
|
601
|
+
getRequestManager(): Promise<IRequestManager>;
|
|
602
|
+
/**
|
|
603
|
+
* @deprecated Use {@link BasicCrawler.getRequestManager|`getRequestManager()`} instead. This returns the
|
|
604
|
+
* crawler's request manager, which is no longer guaranteed to be a {@link RequestQueue}.
|
|
605
|
+
*/
|
|
606
|
+
getRequestQueue(): Promise<IRequestManager>;
|
|
607
|
+
/**
|
|
608
|
+
* Opens the default {@link RequestQueue} — the crawler's own, read from when the caller supplied nothing.
|
|
609
|
+
* @private
|
|
610
|
+
*/
|
|
611
|
+
private openOwnedRequestQueue;
|
|
612
|
+
/**
|
|
613
|
+
* Tells a request manager how long we expect to hold a fetched request, so that one backed by a
|
|
614
|
+
* locking storage backend keeps it reserved for slightly longer than the request handler timeout
|
|
615
|
+
* (with some padding for overhead), but never for less than a minute. This prevents a long-running
|
|
616
|
+
* request from being handed out a second time while it is still being processed — and it works
|
|
617
|
+
* regardless of whether the manager is a plain {@link RequestQueue} or a `RequestManagerTandem`.
|
|
618
|
+
*/
|
|
619
|
+
private applyRequestManagerTimeouts;
|
|
620
|
+
/**
|
|
621
|
+
* Validates a request source's `userData` against the {@link RouteSchemas|Standard Schema} registered
|
|
622
|
+
* for its label on the crawler's schema-router (if any), throwing a {@link RequestValidationError} on
|
|
623
|
+
* mismatch. A no-op when the user's request handler is not a schema-router, or no schema is registered for
|
|
624
|
+
* the request's label. Applied by the crawler on the add paths it owns — `crawler.addRequests`,
|
|
625
|
+
* `crawler.run`, `context.addRequests` and `context.enqueueLinks`.
|
|
626
|
+
*/
|
|
627
|
+
private validateRequestUserData;
|
|
520
628
|
useState<State extends Dictionary = Dictionary>(defaultValue?: State): Promise<State>;
|
|
521
|
-
protected get pendingRequestCountApproximation(): number;
|
|
522
|
-
protected calculateEnqueuedRequestLimit(explicitLimit?: number): number | undefined;
|
|
523
|
-
protected handleSkippedRequest(options: Parameters<SkippedRequestCallback>[0]): Promise<void>;
|
|
524
629
|
/**
|
|
525
630
|
* Adds requests to the queue in batches. By default, it will resolve after the initial batch is added, and continue
|
|
526
631
|
* adding the rest in background. You can configure the batch size via `batchSize` option and the sleep time in between
|
|
527
632
|
* the batches via `waitBetweenBatchesMillis`. If you want to wait for all batches to be added to the queue, you can use
|
|
528
633
|
* the `waitForAllRequestsToBeAdded` promise you get in the response object.
|
|
529
634
|
*
|
|
635
|
+
* Optionally, the requests can be filtered using `include`/`exclude` glob or regexp patterns and an
|
|
636
|
+
* enqueue `strategy` (both AND-ed together, same as {@link CrawlingContext.enqueueLinks|`enqueueLinks`}),
|
|
637
|
+
* relative to `baseUrl`. Unlike `enqueueLinks`, there is no implicit "current page" to anchor the strategy
|
|
638
|
+
* to, so `strategy` defaults to {@link EnqueueStrategy.All|`all`} here.
|
|
639
|
+
*
|
|
530
640
|
* This is an alias for calling `addRequestsBatched()` on the implicit `RequestQueue` for this crawler instance.
|
|
531
641
|
*
|
|
532
642
|
* @param requests The requests to add
|
|
533
643
|
* @param options Options for the request queue
|
|
534
644
|
*/
|
|
535
|
-
addRequests(requests: ReadonlyDeep<
|
|
645
|
+
addRequests(requests: ReadonlyDeep<TypedRequestsLike<Routes>>, options?: CrawlerAddRequestsOptions): Promise<CrawlerAddRequestsResult>;
|
|
536
646
|
/**
|
|
537
647
|
* Pushes data to the specified {@link Dataset}, or the default crawler {@link Dataset} by calling {@link Dataset.pushData}.
|
|
538
648
|
*/
|
|
539
|
-
pushData(data: Parameters<Dataset['pushData']>[0],
|
|
649
|
+
pushData(data: Parameters<Dataset['pushData']>[0], datasetIdentifier?: string | StorageIdentifier): Promise<void>;
|
|
540
650
|
/**
|
|
541
651
|
* Retrieves the specified {@link Dataset}, or the default crawler {@link Dataset}.
|
|
542
652
|
*/
|
|
543
|
-
getDataset(
|
|
653
|
+
getDataset(identifier?: string | StorageIdentifier): Promise<Dataset>;
|
|
544
654
|
/**
|
|
545
655
|
* Retrieves data from the default crawler {@link Dataset} by calling {@link Dataset.getData}.
|
|
546
656
|
*/
|
|
@@ -553,42 +663,63 @@ export declare class BasicCrawler<Context extends CrawlingContext = CrawlingCont
|
|
|
553
663
|
/**
|
|
554
664
|
* Initializes the crawler.
|
|
555
665
|
*/
|
|
556
|
-
protected
|
|
557
|
-
protected runRequestHandler(crawlingContext: CrawlingContext): Promise<void>;
|
|
666
|
+
protected init(): Promise<void>;
|
|
558
667
|
/**
|
|
559
|
-
*
|
|
668
|
+
* The navigation timeout (pre-navigation hooks, navigation, and post-navigation hooks) in milliseconds, used
|
|
669
|
+
* to size the internal request timeout. `BasicCrawler` has no navigation phase, so this is 0; the HTTP and
|
|
670
|
+
* browser crawlers override it with their `navigationTimeoutSecs`.
|
|
560
671
|
*/
|
|
561
|
-
protected
|
|
562
|
-
private isAllowedBasedOnRobotsTxtFile;
|
|
563
|
-
protected getRobotsTxtFileForUrl(url: string): Promise<RobotsTxtFile | undefined>;
|
|
564
|
-
protected _pauseOnMigration(): Promise<void>;
|
|
672
|
+
protected getNavigationTimeoutMillis(): number;
|
|
565
673
|
/**
|
|
566
|
-
*
|
|
674
|
+
* Races the request against the internal timeout (see {@link raceWithTimeout}), sized to outlast the phases
|
|
675
|
+
* that have their own timeout - the navigation, its hooks, and the request handler - so a legitimately slow
|
|
676
|
+
* request, a per-route override, or a low `CRAWLEE_INTERNAL_TIMEOUT` is not cut short mid-phase. It takes
|
|
677
|
+
* whichever is larger: the configured internal timeout, or this request's combined phase budget.
|
|
567
678
|
*/
|
|
568
|
-
private
|
|
679
|
+
private withRequestTimeout;
|
|
569
680
|
/**
|
|
570
|
-
*
|
|
681
|
+
* The request handler timeout for a request with the given route label. A router route may override the
|
|
682
|
+
* crawler's own `requestHandlerTimeoutSecs`; anything else falls back to `fallbackMillis`.
|
|
683
|
+
*
|
|
684
|
+
* @param label The request's route label, or `undefined` for the default route / no specific request.
|
|
685
|
+
* @param fallbackMillis Timeout to use when no route overrides it.
|
|
571
686
|
*/
|
|
572
|
-
|
|
687
|
+
private resolveRequestHandlerTimeoutMillis;
|
|
573
688
|
/**
|
|
574
|
-
*
|
|
575
|
-
*
|
|
576
|
-
* should be ignored and will be reclaimed to the queue once ready.
|
|
689
|
+
* The timeout the router route with the given label asked for, or `undefined` when it did not override one
|
|
690
|
+
* (or the request handler is not a router at all).
|
|
577
691
|
*/
|
|
578
|
-
|
|
692
|
+
private getRouteTimeoutMillis;
|
|
693
|
+
protected runRequestHandler(crawlingContext: ExtendedContext): Promise<void>;
|
|
579
694
|
/**
|
|
580
|
-
*
|
|
581
|
-
*
|
|
695
|
+
* Runs `callback` inside a {@link StorageTransaction}, unless transactional storage is disabled.
|
|
696
|
+
* Deliberately does **not** commit on return - `handleRequest` swallows request handler failures, so
|
|
697
|
+
* a normal return says nothing about success. `handleRequest` owns the outcome.
|
|
582
698
|
*/
|
|
583
|
-
|
|
699
|
+
private runInStorageTransaction;
|
|
584
700
|
/**
|
|
585
|
-
*
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
701
|
+
* Handles blocked request
|
|
702
|
+
*/
|
|
703
|
+
protected throwOnBlockedRequest(statusCode: number): void;
|
|
704
|
+
private isAllowedBasedOnRobotsTxtFile;
|
|
705
|
+
/**
|
|
706
|
+
* Records an HTTP 429 against the URL's domain so the request manager can hold the retry back.
|
|
707
|
+
*
|
|
708
|
+
* @param retryAfterHeader The raw `Retry-After` response header, if the server sent one.
|
|
709
|
+
* @returns `true` if the manager took responsibility for the delay, in which case the caller should throw
|
|
710
|
+
* {@link RequestThrottledError} rather than treating the response as a blocked session.
|
|
711
|
+
*/
|
|
712
|
+
protected recordDomainRateLimit(url: string, retryAfterHeader?: string | null): boolean;
|
|
713
|
+
/** Hands a robots.txt `Crawl-delay` to the request manager, warning if it will not be honoured. */
|
|
714
|
+
private applyCrawlDelay;
|
|
715
|
+
protected getRobotsTxtFileForUrl(url: string): Promise<RobotsTxtFile | undefined>;
|
|
716
|
+
private pauseOnMigration;
|
|
717
|
+
/**
|
|
718
|
+
* Fetches the next request to process from the underlying request provider.
|
|
590
719
|
*/
|
|
591
|
-
|
|
720
|
+
private fetchNextRequest;
|
|
721
|
+
/** Handles a single request - runs the request handler with retries, error handling, and lifecycle management. */
|
|
722
|
+
private handleRequest;
|
|
592
723
|
/**
|
|
593
724
|
* Generator function that yields requests injected with the given crawl depth.
|
|
594
725
|
* @internal
|
|
@@ -598,67 +729,66 @@ export declare class BasicCrawler<Context extends CrawlingContext = CrawlingCont
|
|
|
598
729
|
* Run async callback with given timeout and retry. Returns the result of the callback.
|
|
599
730
|
* @ignore
|
|
600
731
|
*/
|
|
601
|
-
|
|
732
|
+
private timeoutAndRetry;
|
|
602
733
|
/**
|
|
603
|
-
*
|
|
734
|
+
* Whether the request manager has a request ready for processing. A manager that is only `waiting` also gets a
|
|
735
|
+
* wake-up scheduled, so a paced crawl resumes on its clock rather than on the task loop's polling interval.
|
|
604
736
|
*/
|
|
605
|
-
|
|
606
|
-
/**
|
|
607
|
-
* Returns true if both RequestList and RequestQueue have all requests finished.
|
|
608
|
-
*/
|
|
609
|
-
protected _defaultIsFinishedFunction(): Promise<boolean>;
|
|
610
|
-
private _rotateSession;
|
|
737
|
+
private isTaskReadyFunction;
|
|
611
738
|
/**
|
|
612
739
|
* Unwraps errors thrown by the context pipeline to get the actual user error.
|
|
613
|
-
* RequestHandlerError and
|
|
740
|
+
* RequestHandlerError and ContextPipelineCleanupError wrap the actual error.
|
|
614
741
|
*/
|
|
615
742
|
private unwrapError;
|
|
616
743
|
/**
|
|
617
744
|
* Handles errors thrown by user provided requestHandler()
|
|
745
|
+
*
|
|
746
|
+
* @param request The request object, passed separately to circumvent potential dynamic logic in crawlingContext.request
|
|
618
747
|
*/
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
protected _handleFailedRequestHandler(crawlingContext: CrawlingContext, error: Error): Promise<void>;
|
|
748
|
+
private requestFunctionErrorHandler;
|
|
749
|
+
private handleFailedRequestHandler;
|
|
622
750
|
/**
|
|
623
751
|
* Resolves the most verbose error message from a thrown error
|
|
624
752
|
* @param error The error received
|
|
625
753
|
* @returns The message to be logged
|
|
626
754
|
*/
|
|
627
|
-
protected
|
|
628
|
-
protected _canRequestBeRetried(request: Request, error: Error): boolean;
|
|
755
|
+
protected getMessageFromError(error: Error, forceStack?: boolean): string | TimeoutError | undefined;
|
|
629
756
|
/**
|
|
630
|
-
*
|
|
757
|
+
* Whether the session should be spared for this error - either because it was already retired, or because the
|
|
758
|
+
* failure says nothing about the session (a rate limit is a property of the domain).
|
|
631
759
|
*/
|
|
632
|
-
|
|
633
|
-
|
|
760
|
+
private errorAbsolvesSession;
|
|
761
|
+
private canRequestBeRetried;
|
|
634
762
|
/**
|
|
635
|
-
*
|
|
763
|
+
* Ends the run in progress immediately, without waiting for the requests already in flight.
|
|
636
764
|
*
|
|
637
|
-
* This
|
|
765
|
+
* This runs at the end of every {@link BasicCrawler.run|`run()`}, so what it releases is per-run only, and
|
|
766
|
+
* a repeated `run()` has to find everything it needs either intact or re-establishable. What outlives a run is
|
|
767
|
+
* released by {@link BasicCrawler.destroy|`destroy()`} instead.
|
|
638
768
|
*
|
|
639
769
|
* To stop the crawler gracefully (waiting for all running requests to finish), use {@link BasicCrawler.stop|`crawler.stop()`} instead.
|
|
640
770
|
*/
|
|
641
771
|
teardown(): Promise<void>;
|
|
642
|
-
|
|
643
|
-
|
|
772
|
+
/**
|
|
773
|
+
* Releases what the crawler owns beyond a single run — in the browser crawlers, the browser pool. A finished
|
|
774
|
+
* `run()` has already released everything a run owns, so this is only needed before dropping a crawler you
|
|
775
|
+
* could otherwise have run again.
|
|
776
|
+
*/
|
|
777
|
+
destroy(): Promise<void>;
|
|
778
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
779
|
+
protected getCookieHeaderFromRequest(request: Request): string;
|
|
644
780
|
private requestMatchesEnqueueStrategy;
|
|
645
781
|
}
|
|
646
782
|
export interface CreateContextOptions {
|
|
647
|
-
request:
|
|
648
|
-
session
|
|
783
|
+
request: CrawlingRequest;
|
|
784
|
+
session: ISession;
|
|
649
785
|
proxyInfo?: ProxyInfo;
|
|
650
786
|
}
|
|
651
|
-
export interface CrawlerAddRequestsOptions extends AddRequestsBatchedOptions {
|
|
787
|
+
export interface CrawlerAddRequestsOptions extends AddRequestsBatchedOptions, EnqueueUrlsOptions {
|
|
652
788
|
}
|
|
653
789
|
export interface CrawlerAddRequestsResult extends AddRequestsBatchedResult {
|
|
654
790
|
}
|
|
655
791
|
export interface CrawlerRunOptions extends CrawlerAddRequestsOptions {
|
|
656
|
-
/**
|
|
657
|
-
* Whether to purge the RequestQueue before running the crawler again. Defaults to true, so it is possible to reprocess failed requests.
|
|
658
|
-
* When disabled, only new requests will be considered. Note that even a failed request is considered as handled.
|
|
659
|
-
* @default true
|
|
660
|
-
*/
|
|
661
|
-
purgeRequestQueue?: boolean;
|
|
662
792
|
}
|
|
663
793
|
/**
|
|
664
794
|
* Creates new {@link Router} instance that works based on request labels.
|
|
@@ -684,5 +814,5 @@ export interface CrawlerRunOptions extends CrawlerAddRequestsOptions {
|
|
|
684
814
|
* await crawler.run();
|
|
685
815
|
* ```
|
|
686
816
|
*/
|
|
687
|
-
export declare function createBasicRouter<Context extends BasicCrawlingContext = BasicCrawlingContext,
|
|
688
|
-
|
|
817
|
+
export declare function createBasicRouter<Context extends BasicCrawlingContext = BasicCrawlingContext, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<Context['request']>>>(routes?: RouterRoutes<Context, Routes>): RouterHandler<Context, Routes>;
|
|
818
|
+
export declare function createBasicRouter<Context extends BasicCrawlingContext = BasicCrawlingContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, Record<string, UserData>>): RouterHandler<Context, Record<string, UserData>>;
|