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