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