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