@crawlee/basic 4.0.0-beta.9 → 4.0.0-beta.90
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 +17 -13
- package/index.d.ts +1 -2
- package/index.js +0 -2
- package/internals/basic-crawler.d.ts +476 -218
- package/internals/basic-crawler.js +922 -549
- package/internals/send-request.d.ts +3 -6
- package/internals/send-request.js +21 -26
- package/package.json +11 -8
- 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/constants.d.ts +0 -7
- package/internals/constants.d.ts.map +0 -1
- package/internals/constants.js +0 -7
- package/internals/constants.js.map +0 -1
- package/internals/send-request.d.ts.map +0 -1
- package/internals/send-request.js.map +0 -1
- package/tsconfig.build.tsbuildinfo +0 -1
|
@@ -1,46 +1,32 @@
|
|
|
1
|
-
import type { AddRequestsBatchedOptions, AddRequestsBatchedResult,
|
|
2
|
-
import { AutoscaledPool,
|
|
3
|
-
import type { Awaitable, BatchAddRequestsResult, Dictionary, SetStatusMessageOptions } from '@crawlee/types';
|
|
1
|
+
import type { AddRequestsBatchedOptions, AddRequestsBatchedResult, AutoscaledPoolPredicateOptions, ConcurrencySystemOptions, Configuration, CrawleeLogger, CrawlingContext, DatasetExportOptions, EnqueueLinksOptions, EventManager, FinalStatistics, GetUserDataFromRequest, IConcurrencySystem, IProxyConfiguration, IRequestLoader, IRequestManager, Request, RequestsLike, RouterHandler, RouterRoutes, SkippedRequestCallback, Source, StatisticsOptions, StatisticState, StorageIdentifier, TypedRequestsLike } from '@crawlee/core';
|
|
2
|
+
import { AutoscaledPool, ConcurrencySystem, ContextPipeline, Dataset, RequestQueue, Statistics } from '@crawlee/core';
|
|
3
|
+
import type { Awaitable, BaseHttpClient, BatchAddRequestsResult, Dictionary, ISession, ISessionPool, ProxyInfo, SetStatusMessageOptions, StorageBackend } from '@crawlee/types';
|
|
4
4
|
import { RobotsTxtFile } from '@crawlee/utils';
|
|
5
|
-
import type { SetRequired } from 'type-fest';
|
|
6
|
-
import type { Log } from '@apify/log';
|
|
5
|
+
import type { ReadonlyDeep, SetRequired } from 'type-fest';
|
|
7
6
|
import { TimeoutError } from '@apify/timeout';
|
|
8
|
-
export interface BasicCrawlingContext<UserData extends Dictionary = Dictionary> extends CrawlingContext<
|
|
9
|
-
/**
|
|
10
|
-
* This function automatically finds and enqueues links from the current page, adding them to the {@link RequestQueue}
|
|
11
|
-
* currently used by the crawler.
|
|
12
|
-
*
|
|
13
|
-
* Optionally, the function allows you to filter the target links' URLs using an array of globs or regular expressions
|
|
14
|
-
* and override settings of the enqueued {@link Request} objects.
|
|
15
|
-
*
|
|
16
|
-
* Check out the [Crawl a website with relative links](https://crawlee.dev/js/docs/examples/crawl-relative-links) example
|
|
17
|
-
* for more details regarding its usage.
|
|
18
|
-
*
|
|
19
|
-
* **Example usage**
|
|
20
|
-
*
|
|
21
|
-
* ```ts
|
|
22
|
-
* async requestHandler({ enqueueLinks }) {
|
|
23
|
-
* await enqueueLinks({
|
|
24
|
-
* urls: [...],
|
|
25
|
-
* });
|
|
26
|
-
* },
|
|
27
|
-
* ```
|
|
28
|
-
*
|
|
29
|
-
* @param [options] All `enqueueLinks()` parameters are passed via an options object.
|
|
30
|
-
* @returns Promise that resolves to {@link BatchAddRequestsResult} object.
|
|
31
|
-
*/
|
|
32
|
-
enqueueLinks(options?: SetRequired<EnqueueLinksOptions, 'urls'>): Promise<BatchAddRequestsResult>;
|
|
7
|
+
export interface BasicCrawlingContext<UserData extends Dictionary = Dictionary> extends CrawlingContext<UserData> {
|
|
33
8
|
}
|
|
34
|
-
export type RequestHandler<Context extends CrawlingContext =
|
|
35
|
-
|
|
36
|
-
|
|
9
|
+
export type RequestHandler<Context extends CrawlingContext = CrawlingContext> = (inputs: Context) => Awaitable<void>;
|
|
10
|
+
/**
|
|
11
|
+
* An error handler receives the crawling context and the error that was thrown while processing the request.
|
|
12
|
+
*
|
|
13
|
+
* Unlike the {@link RequestHandler}, an error handler may run before the context pipeline has finished
|
|
14
|
+
* building the full context (e.g. when navigation or session setup fails). Therefore only `BaseContext` is
|
|
15
|
+
* guaranteed to be present, while the extra properties added by the pipeline and `extendContext` (the
|
|
16
|
+
* difference between `BaseContext` and `ExtendedContext`) are only available as a `Partial`.
|
|
17
|
+
*/
|
|
18
|
+
export type ErrorHandler<BaseContext extends CrawlingContext = CrawlingContext, ExtendedContext extends BaseContext = BaseContext> = (inputs: BaseContext & Partial<ExtendedContext>, error: Error) => Awaitable<void>;
|
|
19
|
+
export interface StatusMessageCallbackParams<Context extends CrawlingContext = BasicCrawlingContext, Crawler extends BasicCrawler<any, any, any, any> = BasicCrawler<Context>> {
|
|
37
20
|
state: StatisticState;
|
|
38
21
|
crawler: Crawler;
|
|
39
22
|
previousState: StatisticState;
|
|
40
23
|
message: string;
|
|
41
24
|
}
|
|
42
|
-
export type StatusMessageCallback<Context extends CrawlingContext = BasicCrawlingContext, Crawler extends BasicCrawler<any> = BasicCrawler<Context>> = (params: StatusMessageCallbackParams<Context, Crawler>) => Awaitable<void>;
|
|
43
|
-
export
|
|
25
|
+
export type StatusMessageCallback<Context extends CrawlingContext = BasicCrawlingContext, Crawler extends BasicCrawler<any, any, any, any> = BasicCrawler<Context>> = (params: StatusMessageCallbackParams<Context, Crawler>) => Awaitable<void>;
|
|
26
|
+
export type RequireContextPipeline<DefaultContextType extends CrawlingContext, FinalContextType extends DefaultContextType> = DefaultContextType extends FinalContextType ? {} : {
|
|
27
|
+
contextPipelineBuilder: () => ContextPipeline<CrawlingContext, FinalContextType>;
|
|
28
|
+
};
|
|
29
|
+
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']>>> {
|
|
44
30
|
/**
|
|
45
31
|
* User-provided function that performs the logic of the crawler. It is called for each URL to crawl.
|
|
46
32
|
*
|
|
@@ -58,21 +44,64 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
|
|
|
58
44
|
* The exceptions are logged to the request using the
|
|
59
45
|
* {@link Request.pushErrorMessage|`Request.pushErrorMessage()`} function.
|
|
60
46
|
*/
|
|
61
|
-
requestHandler?: RequestHandler<
|
|
47
|
+
requestHandler?: RouterHandler<ExtendedContext, Routes> | RequestHandler<ExtendedContext>;
|
|
48
|
+
/**
|
|
49
|
+
* Allows the user to extend the crawling context with custom functionality (helpers, references, etc.).
|
|
50
|
+
*
|
|
51
|
+
* `extendContext` runs *before* navigation, so the returned members are visible to the
|
|
52
|
+
* `preNavigationHooks`, `postNavigationHooks`, and the `requestHandler` alike. As a consequence,
|
|
53
|
+
* the `context` passed to `extendContext` is the pre-navigation {@link CrawlingContext} and does
|
|
54
|
+
* **not** include navigation-dependent members (e.g. `page`, `response`, `$`, `body`). If you need
|
|
55
|
+
* those, use a `postNavigationHook` or the `requestHandler` instead.
|
|
56
|
+
*
|
|
57
|
+
* **Example usage:**
|
|
58
|
+
*
|
|
59
|
+
* ```javascript
|
|
60
|
+
* import { BasicCrawler } from 'crawlee';
|
|
61
|
+
*
|
|
62
|
+
* // Create a crawler instance
|
|
63
|
+
* const crawler = new BasicCrawler({
|
|
64
|
+
* extendContext(context) => ({
|
|
65
|
+
* async customHelper() {
|
|
66
|
+
* await context.pushData({ url: context.request.url })
|
|
67
|
+
* }
|
|
68
|
+
* }),
|
|
69
|
+
* async requestHandler(context) {
|
|
70
|
+
* await context.customHelper();
|
|
71
|
+
* },
|
|
72
|
+
* });
|
|
73
|
+
* ```
|
|
74
|
+
*/
|
|
75
|
+
extendContext?: (context: CrawlingContext) => Awaitable<ContextExtension>;
|
|
76
|
+
/**
|
|
77
|
+
* *Intended for BasicCrawler subclasses*. Prepares a context pipeline that transforms the initial crawling context into the shape given by the `Context` type parameter.
|
|
78
|
+
*
|
|
79
|
+
* The option is not required if your crawler subclass does not extend the crawling context with custom information or helpers.
|
|
80
|
+
*/
|
|
81
|
+
contextPipelineBuilder?: () => ContextPipeline<CrawlingContext, Context>;
|
|
62
82
|
/**
|
|
63
83
|
* Static list of URLs to be processed.
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
*
|
|
84
|
+
*
|
|
85
|
+
* @deprecated Use the `requestManager` option instead. To combine a read-only loader (such as a `RequestList`)
|
|
86
|
+
* with a writable queue, build a tandem with {@link IRequestLoader.toTandem|`requestList.toTandem(requestQueue)`}
|
|
87
|
+
* and pass the result as `requestManager`. When both `requestList` and `requestQueue` are provided, they are
|
|
88
|
+
* combined into a tandem automatically.
|
|
67
89
|
*/
|
|
68
|
-
requestList?:
|
|
90
|
+
requestList?: IRequestLoader;
|
|
69
91
|
/**
|
|
70
92
|
* Dynamic queue of URLs to be processed. This is useful for recursive crawling of websites.
|
|
71
|
-
*
|
|
72
|
-
*
|
|
73
|
-
* it
|
|
93
|
+
*
|
|
94
|
+
* @deprecated Use the `requestManager` option instead. A `RequestQueue` is itself a request manager, so you can
|
|
95
|
+
* pass it directly as `requestManager`.
|
|
96
|
+
*/
|
|
97
|
+
requestQueue?: RequestQueue;
|
|
98
|
+
/**
|
|
99
|
+
* Manager of requests that should be processed by the crawler. Mutually exclusive with the deprecated
|
|
100
|
+
* `requestQueue` and `requestList` options.
|
|
101
|
+
*
|
|
102
|
+
* If not provided, the crawler will open the default {@link RequestQueue} when it is first needed.
|
|
74
103
|
*/
|
|
75
|
-
|
|
104
|
+
requestManager?: IRequestManager;
|
|
76
105
|
/**
|
|
77
106
|
* Timeout in which the function passed as {@link BasicCrawlerOptions.requestHandler|`requestHandler`} needs to finish, in seconds.
|
|
78
107
|
* @default 60
|
|
@@ -87,7 +116,7 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
|
|
|
87
116
|
* Second argument is the `Error` instance that
|
|
88
117
|
* represents the last error thrown during processing of the request.
|
|
89
118
|
*/
|
|
90
|
-
errorHandler?: ErrorHandler<
|
|
119
|
+
errorHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;
|
|
91
120
|
/**
|
|
92
121
|
* A function to handle requests that failed more than {@link BasicCrawlerOptions.maxRequestRetries|`maxRequestRetries`} times.
|
|
93
122
|
*
|
|
@@ -96,14 +125,11 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
|
|
|
96
125
|
* Second argument is the `Error` instance that
|
|
97
126
|
* represents the last error thrown during processing of the request.
|
|
98
127
|
*/
|
|
99
|
-
failedRequestHandler?: ErrorHandler<
|
|
128
|
+
failedRequestHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;
|
|
100
129
|
/**
|
|
101
130
|
* Specifies the maximum number of retries allowed for a request if its processing fails.
|
|
102
|
-
* This includes retries due to navigation errors or errors thrown from user-supplied
|
|
103
|
-
* (`requestHandler`, `preNavigationHooks`, `postNavigationHooks`).
|
|
104
|
-
*
|
|
105
|
-
* This limit does not apply to retries triggered by session rotation
|
|
106
|
-
* (see {@link BasicCrawlerOptions.maxSessionRotations|`maxSessionRotations`}).
|
|
131
|
+
* This includes retries due to navigation errors, session/proxy errors, or errors thrown from user-supplied
|
|
132
|
+
* functions (`requestHandler`, `preNavigationHooks`, `postNavigationHooks`).
|
|
107
133
|
* @default 3
|
|
108
134
|
*/
|
|
109
135
|
maxRequestRetries?: number;
|
|
@@ -112,14 +138,6 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
|
|
|
112
138
|
* @default 0
|
|
113
139
|
*/
|
|
114
140
|
sameDomainDelaySecs?: number;
|
|
115
|
-
/**
|
|
116
|
-
* Maximum number of session rotations per request.
|
|
117
|
-
* The crawler will automatically rotate the session in case of a proxy error or if it gets blocked by the website.
|
|
118
|
-
*
|
|
119
|
-
* The session rotations are not counted towards the {@link BasicCrawlerOptions.maxRequestRetries|`maxRequestRetries`} limit.
|
|
120
|
-
* @default 10
|
|
121
|
-
*/
|
|
122
|
-
maxSessionRotations?: number;
|
|
123
141
|
/**
|
|
124
142
|
* Maximum number of pages that the crawler will open. The crawl will stop when this limit is reached.
|
|
125
143
|
* This value should always be set in order to prevent infinite loops in misconfigured crawlers.
|
|
@@ -127,29 +145,55 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
|
|
|
127
145
|
*/
|
|
128
146
|
maxRequestsPerCrawl?: number;
|
|
129
147
|
/**
|
|
130
|
-
*
|
|
131
|
-
*
|
|
132
|
-
* and
|
|
133
|
-
* are provided by the crawler and cannot be overridden.
|
|
134
|
-
* However, we can provide a custom implementation of {@link AutoscaledPoolOptions.isFinishedFunction|`isFinishedFunction`}.
|
|
148
|
+
* Maximum depth of the crawl. If not set, the crawl will continue until all requests are processed.
|
|
149
|
+
* Setting this to `0` will only process the initial requests, skipping all links enqueued by `crawlingContext.enqueueLinks` and `crawlingContext.addRequests`.
|
|
150
|
+
* Passing `1` will process the initial requests and all links enqueued by `crawlingContext.enqueueLinks` and `crawlingContext.addRequests` in the handler for initial requests.
|
|
135
151
|
*/
|
|
136
|
-
|
|
152
|
+
maxCrawlDepth?: number;
|
|
153
|
+
/**
|
|
154
|
+
* Lets you override the task-loop predicates (`isFinishedFunction`, `isTaskReadyFunction`) of the crawler's
|
|
155
|
+
* underlying {@link AutoscaledPool}. The `runTaskFunction` is owned by the crawler and cannot be overridden.
|
|
156
|
+
*
|
|
157
|
+
* Concurrency is configured elsewhere — through the `minConcurrency`/`maxConcurrency`/`maxRequestsPerMinute`
|
|
158
|
+
* shortcuts, or a {@link BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} for finer control.
|
|
159
|
+
*/
|
|
160
|
+
autoscaledPoolOptions?: AutoscaledPoolPredicateOptions;
|
|
161
|
+
/**
|
|
162
|
+
* A pre-configured concurrency governor — the component that decides whether there is free compute for one more
|
|
163
|
+
* task. Typically a {@link ConcurrencySystem}, though any {@link IConcurrencySystem} is accepted. All
|
|
164
|
+
* scaling configuration (min/max/desired concurrency, scaling ratios, `maxTasksPerMinute`, snapshotter tuning)
|
|
165
|
+
* lives on the instance itself.
|
|
166
|
+
*
|
|
167
|
+
* Inject the *same* instance into several concurrent crawlers to cap their **combined** concurrency against a
|
|
168
|
+
* single budget. Each crawler still builds and drives its own {@link AutoscaledPool}; only the load/scaling
|
|
169
|
+
* accounting is shared.
|
|
170
|
+
*
|
|
171
|
+
* Mutually exclusive with the `minConcurrency`/`maxConcurrency`/`maxRequestsPerMinute` shortcuts, which configure
|
|
172
|
+
* the default system this one replaces — combining the two throws.
|
|
173
|
+
*
|
|
174
|
+
* You own a supplied system's lifecycle: `start()` it before `run()` (which throws otherwise) and `stop()` it once
|
|
175
|
+
* every crawler borrowing it has finished. The crawler does neither on your behalf.
|
|
176
|
+
*/
|
|
177
|
+
concurrencySystem?: IConcurrencySystem;
|
|
137
178
|
/**
|
|
138
179
|
* Sets the minimum concurrency (parallelism) for the crawl. Shortcut for the
|
|
139
|
-
*
|
|
180
|
+
* {@link ConcurrencySystemOptions.minConcurrency|`minConcurrency`} option of the crawler's default
|
|
181
|
+
* {@link ConcurrencySystem}.
|
|
140
182
|
* > *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.
|
|
141
183
|
* If not sure, it's better to keep the default value and the concurrency will scale up automatically.
|
|
142
184
|
*/
|
|
143
185
|
minConcurrency?: number;
|
|
144
186
|
/**
|
|
145
187
|
* Sets the maximum concurrency (parallelism) for the crawl. Shortcut for the
|
|
146
|
-
*
|
|
188
|
+
* {@link ConcurrencySystemOptions.maxConcurrency|`maxConcurrency`} option of the crawler's default
|
|
189
|
+
* {@link ConcurrencySystem}.
|
|
147
190
|
*/
|
|
148
191
|
maxConcurrency?: number;
|
|
149
192
|
/**
|
|
150
193
|
* The maximum number of requests per minute the crawler should run.
|
|
151
194
|
* By default, this is set to `Infinity`, but we can pass any positive, non-zero integer.
|
|
152
|
-
* Shortcut for the
|
|
195
|
+
* Shortcut for the {@link ConcurrencySystemOptions.maxTasksPerMinute|`maxTasksPerMinute`} option of the
|
|
196
|
+
* crawler's default {@link ConcurrencySystem}.
|
|
153
197
|
*/
|
|
154
198
|
maxRequestsPerMinute?: number;
|
|
155
199
|
/**
|
|
@@ -159,14 +203,14 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
|
|
|
159
203
|
*/
|
|
160
204
|
keepAlive?: boolean;
|
|
161
205
|
/**
|
|
162
|
-
*
|
|
163
|
-
*
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
*
|
|
206
|
+
* An existing session pool instance to use. When provided, the crawler will use this pool directly instead of
|
|
207
|
+
* creating a new one, enabling session sharing across multiple crawlers. The crawler will not tear down a shared
|
|
208
|
+
* pool — the caller is responsible for its lifecycle.
|
|
209
|
+
*
|
|
210
|
+
* Accepts the built-in {@link SessionPool} or any object implementing the {@link ISessionPool} interface,
|
|
211
|
+
* so custom session-management strategies can be plugged in.
|
|
168
212
|
*/
|
|
169
|
-
|
|
213
|
+
sessionPool?: ISessionPool;
|
|
170
214
|
/**
|
|
171
215
|
* Defines the length of the interval for calling the `setStatusMessage` in seconds.
|
|
172
216
|
*/
|
|
@@ -188,6 +232,11 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
|
|
|
188
232
|
* ```
|
|
189
233
|
*/
|
|
190
234
|
statusMessageCallback?: StatusMessageCallback;
|
|
235
|
+
/**
|
|
236
|
+
* HTTP status codes that indicate the session should be retired.
|
|
237
|
+
* @default [401, 403, 429]
|
|
238
|
+
*/
|
|
239
|
+
blockedStatusCodes?: number[];
|
|
191
240
|
/**
|
|
192
241
|
* If set to `true`, the crawler will automatically try to bypass any detected bot protection.
|
|
193
242
|
*
|
|
@@ -199,20 +248,22 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
|
|
|
199
248
|
/**
|
|
200
249
|
* If set to `true`, the crawler will automatically try to fetch the robots.txt file for each domain,
|
|
201
250
|
* and skip those that are not allowed. This also prevents disallowed URLs to be added via `enqueueLinks`.
|
|
251
|
+
*
|
|
252
|
+
* If an object is provided, it may contain a `userAgent` property to specify which user-agent
|
|
253
|
+
* should be used when checking the robots.txt file. If not provided, the default user-agent `*` will be used.
|
|
202
254
|
*/
|
|
203
|
-
respectRobotsTxtFile?: boolean
|
|
255
|
+
respectRobotsTxtFile?: boolean | {
|
|
256
|
+
userAgent?: string;
|
|
257
|
+
};
|
|
204
258
|
/**
|
|
205
259
|
* When a request is skipped for some reason, you can use this callback to act on it.
|
|
206
|
-
* This is currently fired
|
|
260
|
+
* This is currently fired for requests skipped
|
|
261
|
+
* 1. based on robots.txt file,
|
|
262
|
+
* 2. because they don't match enqueueLinks filters,
|
|
263
|
+
* 3. because they are redirected to a URL that doesn't match the enqueueLinks strategy,
|
|
264
|
+
* 4. or because the {@link BasicCrawlerOptions.maxRequestsPerCrawl|`maxRequestsPerCrawl`} limit has been reached
|
|
207
265
|
*/
|
|
208
266
|
onSkippedRequest?: SkippedRequestCallback;
|
|
209
|
-
/** @internal */
|
|
210
|
-
log?: Log;
|
|
211
|
-
/**
|
|
212
|
-
* Enables experimental features of Crawlee, which can alter the behavior of the crawler.
|
|
213
|
-
* WARNING: these options are not guaranteed to be stable and may change or be removed at any time.
|
|
214
|
-
*/
|
|
215
|
-
experiments?: CrawlerExperiments;
|
|
216
267
|
/**
|
|
217
268
|
* Customize the way statistics collecting works, such as logging interval or
|
|
218
269
|
* whether to output them to the Key-Value store.
|
|
@@ -220,24 +271,56 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw
|
|
|
220
271
|
statisticsOptions?: StatisticsOptions;
|
|
221
272
|
/**
|
|
222
273
|
* HTTP client implementation for the `sendRequest` context helper and for plain HTTP crawling.
|
|
223
|
-
* Defaults to
|
|
274
|
+
* Defaults to {@link ImpitHttpClient} when `@crawlee/impit-client` is installed, otherwise {@link FetchHttpClient}.
|
|
224
275
|
*/
|
|
225
276
|
httpClient?: BaseHttpClient;
|
|
226
|
-
}
|
|
227
|
-
/**
|
|
228
|
-
* A set of options that you can toggle to enable experimental features in Crawlee.
|
|
229
|
-
*
|
|
230
|
-
* NOTE: These options will not respect semantic versioning and may be removed or changed at any time. Use at your own risk.
|
|
231
|
-
* If you do use these and encounter issues, please report them to us.
|
|
232
|
-
*/
|
|
233
|
-
export interface CrawlerExperiments {
|
|
234
277
|
/**
|
|
235
|
-
*
|
|
236
|
-
*
|
|
237
|
-
|
|
238
|
-
|
|
278
|
+
* If set, the crawler will be configured for all connections to use
|
|
279
|
+
* the Proxy URLs provided and rotated according to the configuration.
|
|
280
|
+
*/
|
|
281
|
+
proxyConfiguration?: IProxyConfiguration;
|
|
282
|
+
/**
|
|
283
|
+
* Custom configuration to use for this crawler.
|
|
284
|
+
* If provided, the crawler will use its own ServiceLocator instance instead of the global one.
|
|
239
285
|
*/
|
|
240
|
-
|
|
286
|
+
configuration?: Configuration;
|
|
287
|
+
/**
|
|
288
|
+
* Custom storage backend to use for this crawler.
|
|
289
|
+
* If provided, the crawler will use its own ServiceLocator instance instead of the global one.
|
|
290
|
+
*/
|
|
291
|
+
storageBackend?: StorageBackend;
|
|
292
|
+
/**
|
|
293
|
+
* Custom event manager to use for this crawler.
|
|
294
|
+
* If provided, the crawler will use its own ServiceLocator instance instead of the global one.
|
|
295
|
+
*/
|
|
296
|
+
eventManager?: EventManager;
|
|
297
|
+
/**
|
|
298
|
+
* Custom logger to use for this crawler.
|
|
299
|
+
* If provided, the crawler will use its own ServiceLocator instance instead of the global one.
|
|
300
|
+
*/
|
|
301
|
+
logger?: CrawleeLogger;
|
|
302
|
+
/**
|
|
303
|
+
* A unique identifier for the crawler instance. This ID is used to isolate the state returned by
|
|
304
|
+
* {@link BasicCrawler.useState|`crawler.useState()`} from other crawler instances.
|
|
305
|
+
*
|
|
306
|
+
* When multiple crawler instances use `useState()` without an explicit `id`, they will share the same
|
|
307
|
+
* state object for backward compatibility. A warning will be logged in this case.
|
|
308
|
+
*
|
|
309
|
+
* To ensure each crawler has its own isolated state that also persists across script restarts
|
|
310
|
+
* (e.g., during Apify migrations), provide a stable, unique ID for each crawler instance.
|
|
311
|
+
*
|
|
312
|
+
*/
|
|
313
|
+
id?: string;
|
|
314
|
+
/**
|
|
315
|
+
* An array of HTTP response [Status Codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) to be excluded from error consideration.
|
|
316
|
+
* By default, status codes >= 500 trigger errors.
|
|
317
|
+
*/
|
|
318
|
+
ignoreHttpErrorStatusCodes?: number[];
|
|
319
|
+
/**
|
|
320
|
+
* An array of additional HTTP response [Status Codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) to be treated as errors.
|
|
321
|
+
* By default, status codes >= 500 trigger errors.
|
|
322
|
+
*/
|
|
323
|
+
additionalHttpErrorStatusCodes?: number[];
|
|
241
324
|
}
|
|
242
325
|
/**
|
|
243
326
|
* Provides a simple framework for parallel crawling of web pages.
|
|
@@ -251,25 +334,31 @@ export interface CrawlerExperiments {
|
|
|
251
334
|
*
|
|
252
335
|
* `BasicCrawler` invokes the user-provided {@link BasicCrawlerOptions.requestHandler|`requestHandler`}
|
|
253
336
|
* for each {@link Request} object, which represents a single URL to crawl.
|
|
254
|
-
* The {@link Request} objects are fed from the {@link
|
|
255
|
-
*
|
|
256
|
-
*
|
|
257
|
-
*
|
|
258
|
-
*
|
|
337
|
+
* The {@link Request} objects are fed from the {@link IRequestManager|request manager} provided via the
|
|
338
|
+
* {@link BasicCrawlerOptions.requestManager|`requestManager`} constructor option (a {@link RequestQueue} is
|
|
339
|
+
* itself a request manager). If no `requestManager` is provided, the crawler opens the default {@link RequestQueue}
|
|
340
|
+
* either when the {@link BasicCrawler.addRequests|`crawler.addRequests()`} function is called, or if the `requests`
|
|
341
|
+
* parameter (representing the initial requests) of the {@link BasicCrawler.run|`crawler.run()`} function is provided.
|
|
259
342
|
*
|
|
260
|
-
*
|
|
261
|
-
*
|
|
262
|
-
*
|
|
343
|
+
* To read requests from a read-only source such as a {@link RequestList} or {@link SitemapRequestLoader} while
|
|
344
|
+
* still being able to enqueue new ones, combine the loader with a queue into a {@link RequestManagerTandem} using
|
|
345
|
+
* {@link IRequestLoader.toTandem|`requestLoader.toTandem()`} and pass the result as `requestManager`. The tandem
|
|
346
|
+
* first processes URLs from the loader and automatically enqueues them into the queue, ensuring a single URL is not
|
|
347
|
+
* crawled multiple times.
|
|
348
|
+
*
|
|
349
|
+
* > The legacy {@link BasicCrawlerOptions.requestList|`requestList`} and
|
|
350
|
+
* > {@link BasicCrawlerOptions.requestQueue|`requestQueue`} options are deprecated. They are still accepted and
|
|
351
|
+
* > folded into a single `requestManager` (combined into a tandem when both are given), but new code should use
|
|
352
|
+
* > `requestManager` directly.
|
|
263
353
|
*
|
|
264
354
|
* The crawler finishes if there are no more {@link Request} objects to crawl.
|
|
265
355
|
*
|
|
266
356
|
* New requests are only dispatched when there is enough free CPU and memory available,
|
|
267
357
|
* using the functionality provided by the {@link AutoscaledPool} class.
|
|
268
|
-
*
|
|
269
|
-
*
|
|
270
|
-
*
|
|
271
|
-
* {@link
|
|
272
|
-
* underlying {@link AutoscaledPool} constructor are available directly in the `BasicCrawler` constructor.
|
|
358
|
+
* Concurrency is tuned via the {@link BasicCrawlerOptions.minConcurrency|`minConcurrency`},
|
|
359
|
+
* {@link BasicCrawlerOptions.maxConcurrency|`maxConcurrency`} and
|
|
360
|
+
* {@link BasicCrawlerOptions.maxRequestsPerMinute|`maxRequestsPerMinute`} shortcuts, or, for finer control, by
|
|
361
|
+
* injecting a pre-configured {@link BasicCrawlerOptions.concurrencySystem|`concurrencySystem`}.
|
|
273
362
|
*
|
|
274
363
|
* **Example usage:**
|
|
275
364
|
*
|
|
@@ -303,71 +392,147 @@ export interface CrawlerExperiments {
|
|
|
303
392
|
* ```
|
|
304
393
|
* @category Crawlers
|
|
305
394
|
*/
|
|
306
|
-
|
|
307
|
-
|
|
395
|
+
/**
|
|
396
|
+
* Identifies a crawler instance for storage aliasing, `useState()` and status-message events.
|
|
397
|
+
*/
|
|
398
|
+
interface CrawlerIdentity {
|
|
399
|
+
/**
|
|
400
|
+
* 0-based instantiation order across all crawlers in the process.
|
|
401
|
+
* Note that the value can be subject to race conditions between different script invocations.
|
|
402
|
+
*/
|
|
403
|
+
readonly instanceIndex: number;
|
|
404
|
+
/** The user-supplied `id` option, or a fallback derived from `instanceIndex`. */
|
|
405
|
+
readonly id: string;
|
|
406
|
+
/** Whether `id` came from the user (as opposed to being derived from `instanceIndex`). */
|
|
407
|
+
readonly hasExplicitId: boolean;
|
|
408
|
+
}
|
|
409
|
+
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']>>> {
|
|
410
|
+
#private;
|
|
308
411
|
protected static readonly CRAWLEE_STATE_KEY = "CRAWLEE_STATE";
|
|
412
|
+
/**
|
|
413
|
+
* Tracks the number of crawler instances created. The first crawler uses the default
|
|
414
|
+
* request queue; subsequent ones get their own queue via a unique alias so they don't
|
|
415
|
+
* collide.
|
|
416
|
+
*/
|
|
417
|
+
private static instanceCount;
|
|
418
|
+
/**
|
|
419
|
+
* Tracks crawler instances that accessed shared state without having an explicit id.
|
|
420
|
+
* Used to detect and warn about multiple crawlers sharing the same state.
|
|
421
|
+
*/
|
|
422
|
+
private static useStateAnonymousIndices;
|
|
309
423
|
/**
|
|
310
424
|
* A reference to the underlying {@link Statistics} class that collects and logs run statistics for requests.
|
|
311
425
|
*/
|
|
312
426
|
readonly stats: Statistics;
|
|
313
427
|
/**
|
|
314
|
-
*
|
|
315
|
-
*
|
|
428
|
+
* The main request-handling component of the crawler. It manages the requests that the crawler processes,
|
|
429
|
+
* combining any provided request loader and/or queue. It's initialized during the crawler startup or lazily
|
|
430
|
+
* via {@link BasicCrawler.getRequestManager|`getRequestManager()`}.
|
|
316
431
|
*/
|
|
317
|
-
|
|
432
|
+
protected requestManager?: IRequestManager;
|
|
433
|
+
/** Backs the {@link BasicCrawler.sessionPool|`sessionPool`} getter. */
|
|
434
|
+
private sessionPoolDep;
|
|
318
435
|
/**
|
|
319
|
-
*
|
|
320
|
-
*
|
|
321
|
-
* Only available if used by the crawler.
|
|
436
|
+
* A reference to the underlying session pool that manages the crawler's {@link Session|sessions}. Typed as
|
|
437
|
+
* {@link ISessionPool} so custom implementations can be plugged in via the `sessionPool` constructor option.
|
|
322
438
|
*/
|
|
323
|
-
|
|
439
|
+
get sessionPool(): ISessionPool;
|
|
324
440
|
/**
|
|
325
|
-
*
|
|
326
|
-
*
|
|
441
|
+
* Tracks **only** the queue the crawler opens for itself — not the {@link RequestManagerTandem} that may wrap it
|
|
442
|
+
* around a user-supplied `requestList` — so the owned-only purge between repeated `run()` calls never reaches
|
|
443
|
+
* through to a borrowed loader. Filled lazily in {@link BasicCrawler.openOwnedRequestQueue|`openOwnedRequestQueue()`}.
|
|
327
444
|
*/
|
|
328
|
-
|
|
445
|
+
private ownedRequestQueue;
|
|
329
446
|
/**
|
|
330
|
-
*
|
|
447
|
+
* Whether the request-processing-time hint has already been forwarded to the request manager. The hint
|
|
448
|
+
* derives only from `requestHandlerTimeoutMillis` (constant for the crawler's lifetime) and is raise-only,
|
|
449
|
+
* so it only needs to be applied once, at the first async access of the manager.
|
|
450
|
+
*/
|
|
451
|
+
private requestManagerTimeoutsApplied;
|
|
452
|
+
/**
|
|
453
|
+
* Resolves the governor for one run: either the injected
|
|
454
|
+
* {@link BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} (borrowed) or a freshly built default with
|
|
455
|
+
* the concurrency shortcuts folded in (owned, so the crawler starts and stops it).
|
|
456
|
+
*/
|
|
457
|
+
private readonly resolveConcurrencySystem;
|
|
458
|
+
/** As resolved by `_init()`. Absent until the first run, so a `teardown()` before it is a no-op. */
|
|
459
|
+
private concurrencySystemDep?;
|
|
460
|
+
/**
|
|
461
|
+
* A reference to the underlying {@link AutoscaledPool} class that runs the crawler's task loop.
|
|
331
462
|
* > *NOTE:* This property is only initialized after calling the {@link BasicCrawler.run|`crawler.run()`} function.
|
|
332
|
-
* We can use it to
|
|
333
|
-
* to pause the crawler by calling {@link AutoscaledPool.pause|`autoscaledPool.pause()`}
|
|
463
|
+
* We can use it to pause the crawler by calling {@link AutoscaledPool.pause|`autoscaledPool.pause()`}
|
|
334
464
|
* or to abort it by calling {@link AutoscaledPool.abort|`autoscaledPool.abort()`}.
|
|
465
|
+
*
|
|
466
|
+
* The pool only exposes read-only concurrency telemetry. To tune concurrency at runtime, keep a reference to a
|
|
467
|
+
* {@link ConcurrencySystem} and inject it via
|
|
468
|
+
* {@link BasicCrawlerOptions.concurrencySystem|`concurrencySystem`}.
|
|
335
469
|
*/
|
|
336
470
|
autoscaledPool?: AutoscaledPool;
|
|
471
|
+
/**
|
|
472
|
+
* A reference to the underlying {@link IProxyConfiguration} instance that manages the crawler's proxies.
|
|
473
|
+
* Only available if used by the crawler.
|
|
474
|
+
*/
|
|
475
|
+
readonly proxyConfiguration?: IProxyConfiguration;
|
|
337
476
|
/**
|
|
338
477
|
* Default {@link Router} instance that will be used if we don't specify any {@link BasicCrawlerOptions.requestHandler|`requestHandler`}.
|
|
339
478
|
* See {@link Router.addHandler|`router.addHandler()`} and {@link Router.addDefaultHandler|`router.addDefaultHandler()`}.
|
|
340
479
|
*/
|
|
341
|
-
readonly router: RouterHandler<
|
|
480
|
+
readonly router: RouterHandler<Context, Routes>;
|
|
481
|
+
private _basicContextPipeline?;
|
|
482
|
+
/**
|
|
483
|
+
* The basic part of the context pipeline. Unlike the subclass pipeline, this
|
|
484
|
+
* part has no major side effects (e.g. launching a browser). It also makes typing more explicit, as subclass
|
|
485
|
+
* pipelines expect the basic crawler fields to already be present in the context at runtime.
|
|
486
|
+
*
|
|
487
|
+
* Context built with this pipeline can be passed into multiple crawler pipelines at once.
|
|
488
|
+
* This is used e.g. in the {@link AdaptivePlaywrightCrawler|`AdaptivePlaywrightCrawler`}.
|
|
489
|
+
*/
|
|
490
|
+
get basicContextPipeline(): ContextPipeline<{
|
|
491
|
+
request: Request;
|
|
492
|
+
}, CrawlingContext>;
|
|
493
|
+
private _contextPipeline?;
|
|
494
|
+
get contextPipeline(): ContextPipeline<CrawlingContext, ExtendedContext>;
|
|
342
495
|
running: boolean;
|
|
343
496
|
hasFinishedBefore: boolean;
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
protected
|
|
347
|
-
protected
|
|
348
|
-
protected
|
|
349
|
-
|
|
350
|
-
protected
|
|
351
|
-
protected
|
|
352
|
-
protected
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
protected
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
protected
|
|
360
|
-
protected
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
497
|
+
private unexpectedStop;
|
|
498
|
+
get log(): CrawleeLogger;
|
|
499
|
+
protected readonly requestHandler: RequestHandler<ExtendedContext>;
|
|
500
|
+
protected readonly errorHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;
|
|
501
|
+
protected readonly failedRequestHandler?: ErrorHandler<CrawlingContext, ExtendedContext>;
|
|
502
|
+
private requestHandlerTimeoutMillis;
|
|
503
|
+
protected readonly internalTimeoutMillis: number;
|
|
504
|
+
protected readonly maxRequestRetries: number;
|
|
505
|
+
protected readonly maxCrawlDepth?: number;
|
|
506
|
+
private sameDomainDelayMillis;
|
|
507
|
+
private domainAccessedTime;
|
|
508
|
+
protected readonly maxRequestsPerCrawl?: number;
|
|
509
|
+
private get handledRequestsCount();
|
|
510
|
+
private statusMessageLoggingInterval;
|
|
511
|
+
private statusMessageCallback?;
|
|
512
|
+
protected blockedStatusCodes: Set<number>;
|
|
513
|
+
protected readonly additionalHttpErrorStatusCodes: Set<number>;
|
|
514
|
+
private ignoreHttpErrorStatusCodes;
|
|
515
|
+
/**
|
|
516
|
+
* The resolved task-loop options for the crawler's own {@link AutoscaledPool} — the crawler-owned
|
|
517
|
+
* `runTaskFunction`, the (possibly user-overridden) ready/finished predicates and cadence/logging. Concurrency
|
|
518
|
+
* configuration lives on the {@link ConcurrencySystem} instead, and the pool's `consumer` identity is the
|
|
519
|
+
* crawler's own, so neither is settable here.
|
|
520
|
+
*/
|
|
521
|
+
private autoscaledPoolOptions;
|
|
522
|
+
protected readonly httpClient: BaseHttpClient;
|
|
523
|
+
protected readonly retryOnBlocked: boolean;
|
|
524
|
+
private respectRobotsTxtFile;
|
|
525
|
+
protected readonly onSkippedRequest?: SkippedRequestCallback;
|
|
366
526
|
private _closeEvents?;
|
|
367
|
-
private
|
|
527
|
+
private loggedPerRun;
|
|
368
528
|
private readonly robotsTxtFileCache;
|
|
369
|
-
|
|
529
|
+
protected readonly identity: CrawlerIdentity;
|
|
530
|
+
private readonly contextPipelineOptions;
|
|
370
531
|
protected static optionsShape: {
|
|
532
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
533
|
+
contextPipelineBuilder: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
534
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
535
|
+
extendContext: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
|
|
371
536
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
372
537
|
requestList: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
373
538
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
@@ -384,28 +549,44 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlin
|
|
|
384
549
|
maxRequestRetries: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
|
|
385
550
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
386
551
|
sameDomainDelaySecs: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
|
|
387
|
-
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
388
|
-
maxSessionRotations: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
|
|
389
552
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
390
553
|
maxRequestsPerCrawl: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
|
|
554
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
555
|
+
maxCrawlDepth: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
|
|
391
556
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
392
557
|
autoscaledPoolOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
393
558
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
394
|
-
|
|
559
|
+
concurrencySystem: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
395
560
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
396
|
-
|
|
561
|
+
sessionPool: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
562
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
563
|
+
proxyConfiguration: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
397
564
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
398
565
|
statusMessageLoggingInterval: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
|
|
399
566
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
400
567
|
statusMessageCallback: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
|
|
568
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
569
|
+
additionalHttpErrorStatusCodes: import("ow").ArrayPredicate<number>;
|
|
570
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
571
|
+
ignoreHttpErrorStatusCodes: import("ow").ArrayPredicate<number>;
|
|
572
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
573
|
+
blockedStatusCodes: import("ow").ArrayPredicate<number>;
|
|
401
574
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
402
575
|
retryOnBlocked: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
|
|
403
576
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
404
|
-
respectRobotsTxtFile: import("ow").
|
|
577
|
+
respectRobotsTxtFile: import("ow").AnyPredicate<boolean | object>;
|
|
405
578
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
406
579
|
onSkippedRequest: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
|
|
407
580
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
408
581
|
httpClient: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
582
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
583
|
+
configuration: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
584
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
585
|
+
storageBackend: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
586
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
587
|
+
eventManager: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
588
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
589
|
+
logger: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
409
590
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
410
591
|
minConcurrency: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
|
|
411
592
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
@@ -414,17 +595,47 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlin
|
|
|
414
595
|
maxRequestsPerMinute: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
|
|
415
596
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
416
597
|
keepAlive: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
|
|
417
|
-
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
418
|
-
log: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
419
|
-
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
420
|
-
experiments: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
421
598
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
422
599
|
statisticsOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
|
|
600
|
+
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
601
|
+
id: import("ow").StringPredicate & import("ow").BasePredicate<string | undefined>;
|
|
423
602
|
};
|
|
424
603
|
/**
|
|
425
604
|
* All `BasicCrawler` parameters are passed via an options object.
|
|
426
605
|
*/
|
|
427
|
-
constructor(options?: BasicCrawlerOptions<Context
|
|
606
|
+
constructor(options?: BasicCrawlerOptions<Context, ContextExtension, ExtendedContext, Routes> & RequireContextPipeline<CrawlingContext, Context>);
|
|
607
|
+
/**
|
|
608
|
+
* Builds the crawler-owned default {@link ConcurrencySystem} from the resolved
|
|
609
|
+
* `minConcurrency`/`maxConcurrency`/`maxRequestsPerMinute` shortcuts. Not called when a
|
|
610
|
+
* {@link BasicCrawlerOptions.concurrencySystem|`concurrencySystem`} was injected.
|
|
611
|
+
*
|
|
612
|
+
* Subclasses may override this to tune the default system (e.g. {@link HttpCrawler} raises the starting
|
|
613
|
+
* concurrency and relaxes the event loop signal) while still honouring the user's shortcuts.
|
|
614
|
+
*/
|
|
615
|
+
protected createDefaultConcurrencySystem(options: ConcurrencySystemOptions): ConcurrencySystem;
|
|
616
|
+
/**
|
|
617
|
+
* Determines if the given HTTP status code is an error status code given
|
|
618
|
+
* the default behaviour and user-set preferences.
|
|
619
|
+
* @param status
|
|
620
|
+
* @returns `true` if the status code is considered an error, `false` otherwise
|
|
621
|
+
*/
|
|
622
|
+
protected isErrorStatusCode(status: number): boolean;
|
|
623
|
+
/**
|
|
624
|
+
* Builds the basic context pipeline that transforms `{ request }` into a full `CrawlingContext`.
|
|
625
|
+
* This handles base context creation, session resolution, and context helpers.
|
|
626
|
+
*/
|
|
627
|
+
private buildBasicContextPipeline;
|
|
628
|
+
private checkRobotsTxt;
|
|
629
|
+
/**
|
|
630
|
+
* Builds the subclass-specific context pipeline that transforms a `CrawlingContext` into the crawler's target context type.
|
|
631
|
+
* Subclasses should override this to add their own pipeline stages.
|
|
632
|
+
*/
|
|
633
|
+
protected buildContextPipeline(): ContextPipeline<CrawlingContext, CrawlingContext>;
|
|
634
|
+
private createBaseContext;
|
|
635
|
+
private resolveRequest;
|
|
636
|
+
private resolveSession;
|
|
637
|
+
private createContextHelpers;
|
|
638
|
+
private buildFinalContextPipeline;
|
|
428
639
|
/**
|
|
429
640
|
* Checks if the given error is a proxy error by comparing its message to a list of known proxy error messages.
|
|
430
641
|
* Used for retrying requests that failed due to proxy errors.
|
|
@@ -433,15 +644,15 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlin
|
|
|
433
644
|
*/
|
|
434
645
|
protected isProxyError(error: Error): boolean;
|
|
435
646
|
/**
|
|
436
|
-
*
|
|
437
|
-
*
|
|
438
|
-
* @param _crawlingContext The crawling context to check.
|
|
439
|
-
*/
|
|
440
|
-
protected isRequestBlocked(_crawlingContext: Context): Promise<string | false>;
|
|
441
|
-
/**
|
|
647
|
+
* Sets the status message for the current crawler run.
|
|
648
|
+
*
|
|
442
649
|
* This method is periodically called by the crawler, every `statusMessageLoggingInterval` seconds.
|
|
650
|
+
*
|
|
651
|
+
* The message is logged and broadcast via the {@link EventType.STATUS_MESSAGE|`statusMessage`}
|
|
652
|
+
* event. Integrations such as the Apify SDK subscribe to that event and forward the message to
|
|
653
|
+
* their status-reporting backend (e.g. the Apify platform).
|
|
443
654
|
*/
|
|
444
|
-
setStatusMessage(message: string, options?: SetStatusMessageOptions):
|
|
655
|
+
setStatusMessage(message: string, options?: SetStatusMessageOptions): void;
|
|
445
656
|
private getPeriodicLogger;
|
|
446
657
|
/**
|
|
447
658
|
* Runs the crawler. Returns a promise that resolves once all the requests are processed
|
|
@@ -453,15 +664,52 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlin
|
|
|
453
664
|
* @param [requests] The requests to add.
|
|
454
665
|
* @param [options] Options for the request queue.
|
|
455
666
|
*/
|
|
456
|
-
run(requests?:
|
|
667
|
+
run(requests?: TypedRequestsLike<Routes>, options?: CrawlerRunOptions): Promise<FinalStatistics>;
|
|
457
668
|
/**
|
|
458
669
|
* Gracefully stops the current run of the crawler.
|
|
459
670
|
*
|
|
460
671
|
* All the tasks active at the time of calling this method will be allowed to finish.
|
|
672
|
+
*
|
|
673
|
+
* To stop the crawler immediately, use {@link BasicCrawler.teardown|`crawler.teardown()`} instead.
|
|
461
674
|
*/
|
|
462
|
-
stop(
|
|
463
|
-
|
|
675
|
+
stop(reason?: string): void;
|
|
676
|
+
/**
|
|
677
|
+
* Returns the crawler's {@link IRequestManager|request manager}, opening the default {@link RequestQueue}
|
|
678
|
+
* if none has been configured or opened yet.
|
|
679
|
+
*/
|
|
680
|
+
getRequestManager(): Promise<IRequestManager>;
|
|
681
|
+
/**
|
|
682
|
+
* @deprecated Use {@link BasicCrawler.getRequestManager|`getRequestManager()`} instead. This returns the
|
|
683
|
+
* crawler's request manager, which is no longer guaranteed to be a {@link RequestQueue}.
|
|
684
|
+
*/
|
|
685
|
+
getRequestQueue(): Promise<IRequestManager>;
|
|
686
|
+
/**
|
|
687
|
+
* Opens the default {@link RequestQueue}, applies the crawler's timeouts to it and records it as the
|
|
688
|
+
* crawler-owned queue (so it gets purged between repeated `run()` calls).
|
|
689
|
+
* @private
|
|
690
|
+
*/
|
|
691
|
+
private openOwnedRequestQueue;
|
|
692
|
+
/**
|
|
693
|
+
* Tells a request manager how long we expect to hold a fetched request, so that one backed by a
|
|
694
|
+
* locking storage backend keeps it reserved for slightly longer than the request handler timeout
|
|
695
|
+
* (with some padding for overhead), but never for less than a minute. This prevents a long-running
|
|
696
|
+
* request from being handed out a second time while it is still being processed — and it works
|
|
697
|
+
* regardless of whether the manager is a plain {@link RequestQueue} or a `RequestManagerTandem`.
|
|
698
|
+
*/
|
|
699
|
+
private applyRequestManagerTimeouts;
|
|
700
|
+
/**
|
|
701
|
+
* Validates a request source's `userData` against the {@link RouteSchemas|Standard Schema} registered
|
|
702
|
+
* for its label on the crawler's schema-router (if any), throwing a {@link RequestValidationError} on
|
|
703
|
+
* mismatch. A no-op when the user's request handler is not a schema-router, or no schema is registered for
|
|
704
|
+
* the request's label. Applied by the crawler on the add paths it owns — `crawler.addRequests`,
|
|
705
|
+
* `crawler.run`, `context.addRequests` and `context.enqueueLinks`.
|
|
706
|
+
*/
|
|
707
|
+
private validateRequestUserData;
|
|
464
708
|
useState<State extends Dictionary = Dictionary>(defaultValue?: State): Promise<State>;
|
|
709
|
+
protected getPendingRequestCountApproximation(): Promise<number>;
|
|
710
|
+
protected calculateEnqueuedRequestLimit(explicitLimit?: number): Promise<number | undefined>;
|
|
711
|
+
protected handleSkippedRequest(options: Parameters<SkippedRequestCallback>[0]): Promise<void>;
|
|
712
|
+
private logOncePerRun;
|
|
465
713
|
/**
|
|
466
714
|
* Adds requests to the queue in batches. By default, it will resolve after the initial batch is added, and continue
|
|
467
715
|
* adding the rest in background. You can configure the batch size via `batchSize` option and the sleep time in between
|
|
@@ -473,15 +721,15 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlin
|
|
|
473
721
|
* @param requests The requests to add
|
|
474
722
|
* @param options Options for the request queue
|
|
475
723
|
*/
|
|
476
|
-
addRequests(requests:
|
|
724
|
+
addRequests(requests: ReadonlyDeep<TypedRequestsLike<Routes>>, options?: CrawlerAddRequestsOptions): Promise<CrawlerAddRequestsResult>;
|
|
477
725
|
/**
|
|
478
726
|
* Pushes data to the specified {@link Dataset}, or the default crawler {@link Dataset} by calling {@link Dataset.pushData}.
|
|
479
727
|
*/
|
|
480
|
-
pushData(data: Parameters<Dataset['pushData']>[0],
|
|
728
|
+
pushData(data: Parameters<Dataset['pushData']>[0], datasetIdentifier?: string | StorageIdentifier): Promise<void>;
|
|
481
729
|
/**
|
|
482
730
|
* Retrieves the specified {@link Dataset}, or the default crawler {@link Dataset}.
|
|
483
731
|
*/
|
|
484
|
-
getDataset(
|
|
732
|
+
getDataset(identifier?: string | StorageIdentifier): Promise<Dataset>;
|
|
485
733
|
/**
|
|
486
734
|
* Retrieves data from the default crawler {@link Dataset} by calling {@link Dataset.getData}.
|
|
487
735
|
*/
|
|
@@ -491,85 +739,89 @@ export declare class BasicCrawler<Context extends CrawlingContext = BasicCrawlin
|
|
|
491
739
|
* Supported formats are currently 'json' and 'csv', and will be inferred from the `path` automatically.
|
|
492
740
|
*/
|
|
493
741
|
exportData<Data>(path: string, format?: 'json' | 'csv', options?: DatasetExportOptions): Promise<Data[]>;
|
|
742
|
+
/**
|
|
743
|
+
* Initializes the crawler.
|
|
744
|
+
*/
|
|
494
745
|
protected _init(): Promise<void>;
|
|
495
|
-
protected
|
|
746
|
+
protected runRequestHandler(crawlingContext: ExtendedContext): Promise<void>;
|
|
496
747
|
/**
|
|
497
748
|
* Handles blocked request
|
|
498
749
|
*/
|
|
499
|
-
protected _throwOnBlockedRequest(
|
|
750
|
+
protected _throwOnBlockedRequest(statusCode: number): void;
|
|
500
751
|
private isAllowedBasedOnRobotsTxtFile;
|
|
501
752
|
protected getRobotsTxtFileForUrl(url: string): Promise<RobotsTxtFile | undefined>;
|
|
502
|
-
|
|
753
|
+
private pauseOnMigration;
|
|
503
754
|
/**
|
|
504
|
-
* Fetches request
|
|
505
|
-
* and RequestQueue is present then enqueues it to the queue first.
|
|
755
|
+
* Fetches the next request to process from the underlying request provider.
|
|
506
756
|
*/
|
|
507
|
-
|
|
508
|
-
/**
|
|
509
|
-
* Executed when `errorHandler` finishes or the request is successful.
|
|
510
|
-
* Can be used to clean up orphaned browser pages.
|
|
511
|
-
*/
|
|
512
|
-
protected _cleanupContext(_crawlingContext: Context): Promise<void>;
|
|
757
|
+
private fetchNextRequest;
|
|
513
758
|
/**
|
|
514
759
|
* Delays processing of the request based on the `sameDomainDelaySecs` option,
|
|
515
760
|
* adding it back to the queue after the timeout passes. Returns `true` if the request
|
|
516
761
|
* should be ignored and will be reclaimed to the queue once ready.
|
|
517
762
|
*/
|
|
518
|
-
|
|
763
|
+
private delayRequest;
|
|
764
|
+
/** Handles a single request - runs the request handler with retries, error handling, and lifecycle management. */
|
|
765
|
+
private handleRequest;
|
|
766
|
+
/**
|
|
767
|
+
* Wrapper around the crawling context's `enqueueLinks` method:
|
|
768
|
+
* - Injects `crawlDepth` to each request being added based on the crawling context request.
|
|
769
|
+
* - Provides defaults for the `enqueueLinks` options based on the crawler configuration.
|
|
770
|
+
* - These options can be overridden by the user.
|
|
771
|
+
* @internal
|
|
772
|
+
*/
|
|
773
|
+
protected enqueueLinksWithCrawlDepth(options: SetRequired<EnqueueLinksOptions, 'urls'>, request: Request<Dictionary>, requestManager: IRequestManager): Promise<BatchAddRequestsResult>;
|
|
519
774
|
/**
|
|
520
|
-
*
|
|
521
|
-
*
|
|
775
|
+
* Generator function that yields requests injected with the given crawl depth.
|
|
776
|
+
* @internal
|
|
522
777
|
*/
|
|
523
|
-
protected
|
|
778
|
+
protected addCrawlDepthRequestGenerator(requests: RequestsLike, newRequestDepth: number): AsyncGenerator<Source, void, undefined>;
|
|
524
779
|
/**
|
|
525
|
-
* Run async callback with given timeout and retry.
|
|
780
|
+
* Run async callback with given timeout and retry. Returns the result of the callback.
|
|
526
781
|
* @ignore
|
|
527
782
|
*/
|
|
528
|
-
|
|
783
|
+
private timeoutAndRetry;
|
|
529
784
|
/**
|
|
530
785
|
* Returns true if either RequestList or RequestQueue have a request ready for processing.
|
|
531
786
|
*/
|
|
532
|
-
|
|
787
|
+
private isTaskReadyFunction;
|
|
533
788
|
/**
|
|
534
789
|
* Returns true if both RequestList and RequestQueue have all requests finished.
|
|
535
790
|
*/
|
|
536
|
-
|
|
537
|
-
|
|
791
|
+
private defaultIsFinishedFunction;
|
|
792
|
+
/**
|
|
793
|
+
* Unwraps errors thrown by the context pipeline to get the actual user error.
|
|
794
|
+
* RequestHandlerError and ContextPipelineInitializationError wrap the actual error.
|
|
795
|
+
*/
|
|
796
|
+
private unwrapError;
|
|
538
797
|
/**
|
|
539
798
|
* Handles errors thrown by user provided requestHandler()
|
|
799
|
+
*
|
|
800
|
+
* @param request The request object, passed separately to circumvent potential dynamic logic in crawlingContext.request
|
|
540
801
|
*/
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
protected _handleFailedRequestHandler(crawlingContext: Context, error: Error): Promise<void>;
|
|
802
|
+
private requestFunctionErrorHandler;
|
|
803
|
+
private handleFailedRequestHandler;
|
|
544
804
|
/**
|
|
545
805
|
* Resolves the most verbose error message from a thrown error
|
|
546
806
|
* @param error The error received
|
|
547
807
|
* @returns The message to be logged
|
|
548
808
|
*/
|
|
549
809
|
protected _getMessageFromError(error: Error, forceStack?: boolean): string | TimeoutError | undefined;
|
|
550
|
-
|
|
551
|
-
/**
|
|
552
|
-
* Updates handledRequestsCount from possibly stored counts,
|
|
553
|
-
* usually after worker migration. Since one of the stores
|
|
554
|
-
* needs to have priority when both are present,
|
|
555
|
-
* it is the request queue, because generally, the request
|
|
556
|
-
* list will first be dumped into the queue and then left
|
|
557
|
-
* empty.
|
|
558
|
-
*/
|
|
559
|
-
protected _loadHandledRequestCount(): Promise<void>;
|
|
560
|
-
protected _executeHooks<HookLike extends (...args: any[]) => Awaitable<void>>(hooks: HookLike[], ...args: Parameters<HookLike>): Promise<void>;
|
|
810
|
+
private canRequestBeRetried;
|
|
561
811
|
/**
|
|
562
|
-
*
|
|
563
|
-
*
|
|
812
|
+
* Stops the crawler immediately.
|
|
813
|
+
*
|
|
814
|
+
* This method doesn't wait for currently active requests to finish.
|
|
815
|
+
*
|
|
816
|
+
* To stop the crawler gracefully (waiting for all running requests to finish), use {@link BasicCrawler.stop|`crawler.stop()`} instead.
|
|
564
817
|
*/
|
|
565
818
|
teardown(): Promise<void>;
|
|
566
819
|
protected _getCookieHeaderFromRequest(request: Request): string;
|
|
567
|
-
private
|
|
568
|
-
protected requestMatchesEnqueueStrategy(request: Request): boolean;
|
|
820
|
+
private requestMatchesEnqueueStrategy;
|
|
569
821
|
}
|
|
570
822
|
export interface CreateContextOptions {
|
|
571
823
|
request: Request;
|
|
572
|
-
session
|
|
824
|
+
session: ISession;
|
|
573
825
|
proxyInfo?: ProxyInfo;
|
|
574
826
|
}
|
|
575
827
|
export interface CrawlerAddRequestsOptions extends AddRequestsBatchedOptions {
|
|
@@ -578,9 +830,14 @@ export interface CrawlerAddRequestsResult extends AddRequestsBatchedResult {
|
|
|
578
830
|
}
|
|
579
831
|
export interface CrawlerRunOptions extends CrawlerAddRequestsOptions {
|
|
580
832
|
/**
|
|
581
|
-
*
|
|
582
|
-
*
|
|
583
|
-
*
|
|
833
|
+
* Controls whether the request queue is purged between repeated `run()` calls on the same crawler instance.
|
|
834
|
+
* Purging clears all requests and resets internal counters, allowing the same URLs to be processed again.
|
|
835
|
+
*
|
|
836
|
+
* - **`undefined`** (default) — only the crawler's own (auto-created) queue is purged.
|
|
837
|
+
* A user-supplied `requestQueue` is left untouched.
|
|
838
|
+
* - **`true`** — the queue is always purged, even if it was supplied by the user.
|
|
839
|
+
* - **`false`** — nothing is purged. Only genuinely new requests will be processed;
|
|
840
|
+
* note that even a failed request is considered handled.
|
|
584
841
|
*/
|
|
585
842
|
purgeRequestQueue?: boolean;
|
|
586
843
|
}
|
|
@@ -608,5 +865,6 @@ export interface CrawlerRunOptions extends CrawlerAddRequestsOptions {
|
|
|
608
865
|
* await crawler.run();
|
|
609
866
|
* ```
|
|
610
867
|
*/
|
|
611
|
-
export declare function createBasicRouter<Context extends BasicCrawlingContext = BasicCrawlingContext,
|
|
612
|
-
|
|
868
|
+
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>;
|
|
869
|
+
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>>;
|
|
870
|
+
export {};
|