@crawlee/cheerio 3.0.0-alpha.2 → 3.0.0-alpha.22

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/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from '@crawlee/basic';
2
+ export * from './internals/cheerio-crawler';
3
+ //# sourceMappingURL=index.d.ts.map
package/index.d.ts.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,6BAA6B,CAAC"}
package/index.js ADDED
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ tslib_1.__exportStar(require("@crawlee/basic"), exports);
5
+ tslib_1.__exportStar(require("./internals/cheerio-crawler"), exports);
6
+ //# sourceMappingURL=index.js.map
package/index.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,yDAA+B;AAC/B,sEAA4C"}
package/index.mjs ADDED
@@ -0,0 +1,65 @@
1
+ import mod from "./index.js";
2
+
3
+ export default mod;
4
+ export const API_PROCESSED_REQUESTS_DELAY_MILLIS = mod.API_PROCESSED_REQUESTS_DELAY_MILLIS;
5
+ export const AutoscaledPool = mod.AutoscaledPool;
6
+ export const BASIC_CRAWLER_TIMEOUT_BUFFER_SECS = mod.BASIC_CRAWLER_TIMEOUT_BUFFER_SECS;
7
+ export const BasicCrawler = mod.BasicCrawler;
8
+ export const CheerioCrawler = mod.CheerioCrawler;
9
+ export const Configuration = mod.Configuration;
10
+ export const CookieParseError = mod.CookieParseError;
11
+ export const CrawlerExtension = mod.CrawlerExtension;
12
+ export const DATASET_ITERATORS_DEFAULT_LIMIT = mod.DATASET_ITERATORS_DEFAULT_LIMIT;
13
+ export const Dataset = mod.Dataset;
14
+ export const EVENT_SESSION_RETIRED = mod.EVENT_SESSION_RETIRED;
15
+ export const EnqueueStrategy = mod.EnqueueStrategy;
16
+ export const EventManager = mod.EventManager;
17
+ export const EventType = mod.EventType;
18
+ export const KeyValueStore = mod.KeyValueStore;
19
+ export const LocalEventManager = mod.LocalEventManager;
20
+ export const Log = mod.Log;
21
+ export const LogLevel = mod.LogLevel;
22
+ export const Logger = mod.Logger;
23
+ export const LoggerJson = mod.LoggerJson;
24
+ export const LoggerText = mod.LoggerText;
25
+ export const MAX_QUERIES_FOR_CONSISTENCY = mod.MAX_QUERIES_FOR_CONSISTENCY;
26
+ export const ProxyConfiguration = mod.ProxyConfiguration;
27
+ export const QUERY_HEAD_BUFFER = mod.QUERY_HEAD_BUFFER;
28
+ export const QUERY_HEAD_MIN_LENGTH = mod.QUERY_HEAD_MIN_LENGTH;
29
+ export const REQUESTS_PERSISTENCE_KEY = mod.REQUESTS_PERSISTENCE_KEY;
30
+ export const Request = mod.Request;
31
+ export const RequestList = mod.RequestList;
32
+ export const RequestQueue = mod.RequestQueue;
33
+ export const STATE_PERSISTENCE_KEY = mod.STATE_PERSISTENCE_KEY;
34
+ export const STATUS_CODES_BLOCKED = mod.STATUS_CODES_BLOCKED;
35
+ export const STORAGE_CONSISTENCY_DELAY_MILLIS = mod.STORAGE_CONSISTENCY_DELAY_MILLIS;
36
+ export const Session = mod.Session;
37
+ export const SessionPool = mod.SessionPool;
38
+ export const Snapshotter = mod.Snapshotter;
39
+ export const Statistics = mod.Statistics;
40
+ export const StorageManager = mod.StorageManager;
41
+ export const SystemStatus = mod.SystemStatus;
42
+ export const checkAndSerialize = mod.checkAndSerialize;
43
+ export const cheerioCrawlerEnqueueLinks = mod.cheerioCrawlerEnqueueLinks;
44
+ export const chunkBySize = mod.chunkBySize;
45
+ export const constructGlobObjectsFromGlobs = mod.constructGlobObjectsFromGlobs;
46
+ export const constructRegExpObjectsFromPseudoUrls = mod.constructRegExpObjectsFromPseudoUrls;
47
+ export const constructRegExpObjectsFromRegExps = mod.constructRegExpObjectsFromRegExps;
48
+ export const createDeserialize = mod.createDeserialize;
49
+ export const createRequestOptions = mod.createRequestOptions;
50
+ export const createRequests = mod.createRequests;
51
+ export const deserializeArray = mod.deserializeArray;
52
+ export const diffCookies = mod.diffCookies;
53
+ export const enqueueLinks = mod.enqueueLinks;
54
+ export const getCookiesFromResponse = mod.getCookiesFromResponse;
55
+ export const getRequestId = mod.getRequestId;
56
+ export const handleRequestTimeout = mod.handleRequestTimeout;
57
+ export const log = mod.log;
58
+ export const maybeStringify = mod.maybeStringify;
59
+ export const mergeCookies = mod.mergeCookies;
60
+ export const resolveBaseUrl = mod.resolveBaseUrl;
61
+ export const serializeArray = mod.serializeArray;
62
+ export const storage = mod.storage;
63
+ export const updateEnqueueLinksPatternCache = mod.updateEnqueueLinksPatternCache;
64
+ export const validateGlobPattern = mod.validateGlobPattern;
65
+ export const validators = mod.validators;
@@ -0,0 +1,547 @@
1
+ /// <reference types="node" />
2
+ import { BasicCrawler, BasicCrawlerOptions } from '@crawlee/basic';
3
+ import { CrawlerExtension, CrawlerHandleFailedRequestInput, CrawlingContext, EnqueueLinksOptions, ProxyConfiguration, ProxyInfo, Request, RequestQueue, Session, storage } from '@crawlee/core';
4
+ import { Awaitable, CheerioRoot, Dictionary } from '@crawlee/utils';
5
+ import { RequestLike, ResponseLike } from 'content-type';
6
+ import { OptionsInit } from 'got-scraping';
7
+ import { IncomingMessage } from 'http';
8
+ export interface CheerioFailedRequestHandlerInput<JSONData = Dictionary> extends CrawlerHandleFailedRequestInput, CheerioRequestHandlerInputs<JSONData> {
9
+ }
10
+ export declare type CheerioFailedRequestHandler<JSONData = Dictionary> = (inputs: CheerioFailedRequestHandlerInput<JSONData>) => Awaitable<void>;
11
+ export interface CheerioCrawlerOptions<JSONData = Dictionary> extends Omit<BasicCrawlerOptions<CheerioCrawlingContext<JSONData>>, 'requestHandler' | 'handleRequestFunction' | 'failedRequestHandler' | 'handleFailedRequestFunction' | 'handleRequestTimeoutSecs'> {
12
+ /**
13
+ * User-provided function that performs the logic of the crawler. It is called for each page
14
+ * loaded and parsed by the crawler.
15
+ *
16
+ * The function receives the following object as an argument:
17
+ * ```
18
+ * {
19
+ * // The Cheerio object's function with the parsed HTML.
20
+ * $: Cheerio,
21
+ *
22
+ * // The request body of the web page, whose type depends on the content type.
23
+ * body: String|Buffer,
24
+ *
25
+ * // The parsed object from JSON for responses with the "application/json" content types.
26
+ * // For other content types it's null.
27
+ * json: Object,
28
+ *
29
+ * // Request object with details of the requested web page
30
+ * request: Request,
31
+ *
32
+ * // Parsed Content-Type HTTP header: { type, encoding }
33
+ * contentType: Object,
34
+ *
35
+ * // An instance of Node's http.IncomingMessage object,
36
+ * response: Object,
37
+ *
38
+ * // Session object, useful to work around anti-scraping protections
39
+ * session: Session
40
+ *
41
+ * // ProxyInfo object with information about currently used proxy
42
+ * proxyInfo: ProxyInfo
43
+ *
44
+ * // The running cheerio crawler instance.
45
+ * crawler: CheerioCrawler
46
+ * }
47
+ * ```
48
+ *
49
+ * Type of `body` depends on the `Content-Type` header of the web page:
50
+ * - String for `text/html`, `application/xhtml+xml`, `application/xml` MIME content types
51
+ * - Buffer for others MIME content types
52
+ *
53
+ * Parsed `Content-Type` header using
54
+ * [content-type package](https://www.npmjs.com/package/content-type)
55
+ * is stored in `contentType`.
56
+ *
57
+ * Cheerio is available only for HTML and XML content types.
58
+ *
59
+ * With the {@link Request} object representing the URL to crawl.
60
+ *
61
+ * If the function returns, the returned promise is awaited by the crawler.
62
+ *
63
+ * If the function throws an exception, the crawler will try to re-crawl the
64
+ * request later, up to `option.maxRequestRetries` times.
65
+ * If all the retries fail, the crawler calls the function
66
+ * provided to the `handleFailedRequestFunction` parameter.
67
+ * To make this work, you should **always**
68
+ * let your function throw exceptions rather than catch them.
69
+ * The exceptions are logged to the request using the
70
+ * {@link Request.pushErrorMessage} function.
71
+ */
72
+ requestHandler: CheerioRequestHandler<JSONData>;
73
+ /**
74
+ * User-provided function that performs the logic of the crawler. It is called for each page
75
+ * loaded and parsed by the crawler.
76
+ *
77
+ * The function receives the following object as an argument:
78
+ * ```
79
+ * {
80
+ * // The Cheerio object's function with the parsed HTML.
81
+ * $: Cheerio,
82
+ *
83
+ * // The request body of the web page, whose type depends on the content type.
84
+ * body: String|Buffer,
85
+ *
86
+ * // The parsed object from JSON for responses with the "application/json" content types.
87
+ * // For other content types it's null.
88
+ * json: Object,
89
+ *
90
+ * // Request object with details of the requested web page
91
+ * request: Request,
92
+ *
93
+ * // Parsed Content-Type HTTP header: { type, encoding }
94
+ * contentType: Object,
95
+ *
96
+ * // An instance of Node's http.IncomingMessage object,
97
+ * response: Object,
98
+ *
99
+ * // Session object, useful to work around anti-scraping protections
100
+ * session: Session
101
+ *
102
+ * // ProxyInfo object with information about currently used proxy
103
+ * proxyInfo: ProxyInfo
104
+ *
105
+ * // The running cheerio crawler instance.
106
+ * crawler: CheerioCrawler
107
+ * }
108
+ * ```
109
+ *
110
+ * Type of `body` depends on the `Content-Type` header of the web page:
111
+ * - String for `text/html`, `application/xhtml+xml`, `application/xml` MIME content types
112
+ * - Buffer for others MIME content types
113
+ *
114
+ * Parsed `Content-Type` header using
115
+ * [content-type package](https://www.npmjs.com/package/content-type)
116
+ * is stored in `contentType`.
117
+ *
118
+ * Cheerio is available only for HTML and XML content types.
119
+ *
120
+ * With the {@link Request} object representing the URL to crawl.
121
+ *
122
+ * If the function returns, the returned promise is awaited by the crawler.
123
+ *
124
+ * If the function throws an exception, the crawler will try to re-crawl the
125
+ * request later, up to `option.maxRequestRetries` times.
126
+ * If all the retries fail, the crawler calls the function
127
+ * provided to the `handleFailedRequestFunction` parameter.
128
+ * To make this work, you should **always**
129
+ * let your function throw exceptions rather than catch them.
130
+ * The exceptions are logged to the request using the
131
+ * {@link Request.pushErrorMessage} function.
132
+ *
133
+ * @deprecated `handlePageFunction` has been renamed to `requestHandler` and will be removed in a future version.
134
+ */
135
+ handlePageFunction?: CheerioRequestHandler<JSONData>;
136
+ /**
137
+ * Timeout in which the HTTP request to the resource needs to finish, given in seconds.
138
+ */
139
+ requestTimeoutSecs?: number;
140
+ /**
141
+ * If set to true, SSL certificate errors will be ignored.
142
+ */
143
+ ignoreSslErrors?: boolean;
144
+ /**
145
+ * If set, `CheerioCrawler` will be configured for all connections to use
146
+ * [Apify Proxy](https://console.apify.com/proxy) or your own Proxy URLs provided and rotated according to the configuration.
147
+ * For more information, see the [documentation](https://docs.apify.com/proxy).
148
+ */
149
+ proxyConfiguration?: ProxyConfiguration;
150
+ /**
151
+ * A function to handle requests that failed more than `option.maxRequestRetries` times.
152
+ * The function receives the following object as an argument:
153
+ * ```
154
+ * {
155
+ * error: Error,
156
+ * request: Request,
157
+ * session: Session,
158
+ * $: Cheerio,
159
+ * body: String|Buffer,
160
+ * json: Object,
161
+ * contentType: Object,
162
+ * response: Object,
163
+ * proxyInfo: ProxyInfo,
164
+ * crawler: CheerioCrawler,
165
+ * }
166
+ * ```
167
+ * where the {@link Request} instance corresponds to the failed request, and the `Error` instance
168
+ * represents the last error thrown during processing of the request.
169
+ *
170
+ * See [source code](https://github.com/apify/apify-js/blob/master/src/crawlers/cheerio_crawler.js#L13)
171
+ * for the default implementation of this function.
172
+ */
173
+ failedRequestHandler?: CheerioFailedRequestHandler<JSONData>;
174
+ /**
175
+ * A function to handle requests that failed more than `option.maxRequestRetries` times.
176
+ * The function receives the following object as an argument:
177
+ * ```
178
+ * {
179
+ * error: Error,
180
+ * request: Request,
181
+ * session: Session,
182
+ * $: Cheerio,
183
+ * body: String|Buffer,
184
+ * json: Object,
185
+ * contentType: Object,
186
+ * response: Object,
187
+ * proxyInfo: ProxyInfo,
188
+ * crawler: CheerioCrawler,
189
+ * }
190
+ * ```
191
+ * where the {@link Request} instance corresponds to the failed request, and the `Error` instance
192
+ * represents the last error thrown during processing of the request.
193
+ *
194
+ * See [source code](https://github.com/apify/apify-js/blob/master/src/crawlers/cheerio_crawler.js#L13)
195
+ * for the default implementation of this function.
196
+ *
197
+ * @deprecated `handleFailedRequestFunction` has been renamed to `failedRequestHandler` and will be removed in a future version.
198
+ */
199
+ handleFailedRequestFunction?: CheerioFailedRequestHandler<JSONData>;
200
+ /**
201
+ * Async functions that are sequentially evaluated before the navigation. Good for setting additional cookies
202
+ * or browser properties before navigation. The function accepts two parameters, `crawlingContext` and `gotOptions`,
203
+ * which are passed to the `requestAsBrowser()` function the crawler calls to navigate.
204
+ * Example:
205
+ * ```
206
+ * preNavigationHooks: [
207
+ * async (crawlingContext, gotOptions) => {
208
+ * // ...
209
+ * },
210
+ * ]
211
+ * ```
212
+ */
213
+ preNavigationHooks?: CheerioHook<JSONData>[];
214
+ /**
215
+ * Async functions that are sequentially evaluated after the navigation. Good for checking if the navigation was successful.
216
+ * The function accepts `crawlingContext` as the only parameter.
217
+ * Example:
218
+ * ```
219
+ * postNavigationHooks: [
220
+ * async (crawlingContext) => {
221
+ * // ...
222
+ * },
223
+ * ]
224
+ * ```
225
+ */
226
+ postNavigationHooks?: CheerioHook<JSONData>[];
227
+ /**
228
+ * An array of [MIME types](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types)
229
+ * you want the crawler to load and process. By default, only `text/html` and `application/xhtml+xml` MIME types are supported.
230
+ */
231
+ additionalMimeTypes?: string[];
232
+ /**
233
+ * By default `CheerioCrawler` will extract correct encoding from the HTTP response headers.
234
+ * Sadly, there are some websites which use invalid headers. Those are encoded using the UTF-8 encoding.
235
+ * If those sites actually use a different encoding, the response will be corrupted. You can use
236
+ * `suggestResponseEncoding` to fall back to a certain encoding, if you know that your target website uses it.
237
+ * To force a certain encoding, disregarding the response headers, use {@link CheerioCrawlerOptions.forceResponseEncoding}
238
+ * ```
239
+ * // Will fall back to windows-1250 encoding if none found
240
+ * suggestResponseEncoding: 'windows-1250'
241
+ * ```
242
+ */
243
+ suggestResponseEncoding?: string;
244
+ /**
245
+ * By default `CheerioCrawler` will extract correct encoding from the HTTP response headers. Use `forceResponseEncoding`
246
+ * to force a certain encoding, disregarding the response headers.
247
+ * To only provide a default for missing encodings, use {@link CheerioCrawlerOptions.suggestResponseEncoding}
248
+ * ```
249
+ * // Will force windows-1250 encoding even if headers say otherwise
250
+ * forceResponseEncoding: 'windows-1250'
251
+ * ```
252
+ */
253
+ forceResponseEncoding?: string;
254
+ /**
255
+ * Automatically saves cookies to Session. Works only if Session Pool is used.
256
+ *
257
+ * It parses cookie from response "set-cookie" header saves or updates cookies for session and once the session is used for next request.
258
+ * It passes the "Cookie" header to the request with the session cookies.
259
+ */
260
+ persistCookiesPerSession?: boolean;
261
+ }
262
+ export interface PrepareRequestInputs<JSONData = Dictionary> {
263
+ /**
264
+ * Original instance of the {@link Request} object. Must be modified in-place.
265
+ */
266
+ request: Request;
267
+ /**
268
+ * The current session
269
+ */
270
+ session?: Session;
271
+ /**
272
+ * An object with information about currently used proxy by the crawler
273
+ * and configured by the {@link ProxyConfiguration} class.
274
+ */
275
+ proxyInfo?: ProxyInfo;
276
+ crawler?: CheerioCrawler<JSONData>;
277
+ }
278
+ export declare type PrepareRequest<JSONData = Dictionary> = (inputs: PrepareRequestInputs<JSONData>) => Awaitable<void>;
279
+ export declare type CheerioHook<JSONData = Dictionary> = (crawlingContext: CheerioCrawlingContext<JSONData>, gotOptions: OptionsInit) => Awaitable<void>;
280
+ export interface PostResponseInputs<JSONData = Dictionary> {
281
+ /**
282
+ * stream
283
+ */
284
+ response?: IncomingMessage;
285
+ /**
286
+ * Original instance fo the {Request} object. Must be modified in-place.
287
+ */
288
+ request: Request;
289
+ /**
290
+ * The current session
291
+ */
292
+ session?: Session;
293
+ /**
294
+ * An object with information about currently used proxy by the crawler
295
+ * and configured by the {@link ProxyConfiguration} class.
296
+ */
297
+ proxyInfo?: ProxyInfo;
298
+ crawler: CheerioCrawler<JSONData>;
299
+ }
300
+ export declare type PostResponse<JSONData = Dictionary> = (inputs: PostResponseInputs<JSONData>) => Awaitable<void>;
301
+ export interface CheerioRequestHandlerInputs<JSONData = Dictionary> extends CrawlingContext {
302
+ /**
303
+ * The [Cheerio](https://cheerio.js.org/) object with parsed HTML.
304
+ */
305
+ $: CheerioRoot;
306
+ /**
307
+ * The request body of the web page.
308
+ */
309
+ body: (string | Buffer);
310
+ /**
311
+ * The parsed object from JSON string if the response contains the content type application/json.
312
+ */
313
+ json: JSONData;
314
+ /**
315
+ * Parsed `Content-Type header: { type, encoding }`.
316
+ */
317
+ contentType: {
318
+ type: string;
319
+ encoding: string;
320
+ };
321
+ crawler: CheerioCrawler<JSONData>;
322
+ response: IncomingMessage;
323
+ enqueueLinks: (options?: CheerioCrawlerEnqueueLinksOptions) => Promise<storage.BatchAddRequestsResult>;
324
+ }
325
+ export declare type CheerioCrawlingContext<JSONData = Dictionary> = CheerioRequestHandlerInputs<JSONData>;
326
+ export declare type CheerioRequestHandler<JSONData = Dictionary> = (inputs: CheerioRequestHandlerInputs<JSONData>) => Awaitable<void>;
327
+ export declare type CheerioCrawlerEnqueueLinksOptions = Omit<EnqueueLinksOptions, 'urls' | 'requestQueue'>;
328
+ /**
329
+ * Provides a framework for the parallel crawling of web pages using plain HTTP requests and
330
+ * [cheerio](https://www.npmjs.com/package/cheerio) HTML parser.
331
+ * The URLs to crawl are fed either from a static list of URLs
332
+ * or from a dynamic queue of URLs enabling recursive crawling of websites.
333
+ *
334
+ * Since `CheerioCrawler` uses raw HTTP requests to download web pages,
335
+ * it is very fast and efficient on data bandwidth. However, if the target website requires JavaScript
336
+ * to display the content, you might need to use {@link PuppeteerCrawler} or {@link PlaywrightCrawler} instead,
337
+ * because it loads the pages using full-featured headless Chrome browser.
338
+ *
339
+ * `CheerioCrawler` downloads each URL using a plain HTTP request,
340
+ * parses the HTML content using [Cheerio](https://www.npmjs.com/package/cheerio)
341
+ * and then invokes the user-provided {@link CheerioCrawlerOptions.requestHandler} to extract page data
342
+ * using a [jQuery](https://jquery.com/)-like interface to the parsed HTML DOM.
343
+ *
344
+ * The source URLs are represented using {@link Request} objects that are fed from
345
+ * {@link RequestList} or {@link RequestQueue} instances provided by the {@link CheerioCrawlerOptions.requestList}
346
+ * or {@link CheerioCrawlerOptions.requestQueue} constructor options, respectively.
347
+ *
348
+ * If both {@link CheerioCrawlerOptions.requestList} and {@link CheerioCrawlerOptions.requestQueue} are used,
349
+ * the instance first processes URLs from the {@link RequestList} and automatically enqueues all of them
350
+ * to {@link RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.
351
+ *
352
+ * The crawler finishes when there are no more {@link Request} objects to crawl.
353
+ *
354
+ * We can use the `preNavigationHooks` to adjust `gotOptions`:
355
+ *
356
+ * ```
357
+ * preNavigationHooks: [
358
+ * (crawlingContext, gotOptions) => {
359
+ * // ...
360
+ * },
361
+ * ]
362
+ * ```
363
+ *
364
+ * By default, `CheerioCrawler` only processes web pages with the `text/html`
365
+ * and `application/xhtml+xml` MIME content types (as reported by the `Content-Type` HTTP header),
366
+ * and skips pages with other content types. If you want the crawler to process other content types,
367
+ * use the {@link CheerioCrawlerOptions.additionalMimeTypes} constructor option.
368
+ * Beware that the parsing behavior differs for HTML, XML, JSON and other types of content.
369
+ * For details, see {@link CheerioCrawlerOptions.requestHandler}.
370
+ *
371
+ * New requests are only dispatched when there is enough free CPU and memory available,
372
+ * using the functionality provided by the {@link AutoscaledPool} class.
373
+ * All {@link AutoscaledPool} configuration options can be passed to the `autoscaledPoolOptions`
374
+ * parameter of the `CheerioCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency`
375
+ * {@link AutoscaledPool} options are available directly in the `CheerioCrawler` constructor.
376
+ *
377
+ * **Example usage:**
378
+ *
379
+ * ```javascript
380
+ * // Prepare a list of URLs to crawl
381
+ * const requestList = new RequestList({
382
+ * sources: [
383
+ * { url: 'http://www.example.com/page-1' },
384
+ * { url: 'http://www.example.com/page-2' },
385
+ * ],
386
+ * });
387
+ * await requestList.initialize();
388
+ *
389
+ * // Crawl the URLs
390
+ * const crawler = new CheerioCrawler({
391
+ * requestList,
392
+ * handlePageFunction: async ({ request, response, body, contentType, $ }) => {
393
+ * const data = [];
394
+ *
395
+ * // Do some data extraction from the page with Cheerio.
396
+ * $('.some-collection').each((index, el) => {
397
+ * data.push({ title: $(el).find('.some-title').text() });
398
+ * });
399
+ *
400
+ * // Save the data to dataset.
401
+ * await Actor.pushData({
402
+ * url: request.url,
403
+ * html: body,
404
+ * data,
405
+ * })
406
+ * },
407
+ * });
408
+ *
409
+ * await crawler.run();
410
+ * ```
411
+ * @category Crawlers
412
+ */
413
+ export declare class CheerioCrawler<JSONData = Dictionary> extends BasicCrawler<CheerioCrawlingContext<JSONData>, CheerioFailedRequestHandlerInput<JSONData>> {
414
+ /**
415
+ * A reference to the underlying {@link ProxyConfiguration} class that manages the crawler's proxies.
416
+ * Only available if used by the crawler.
417
+ */
418
+ proxyConfiguration?: ProxyConfiguration;
419
+ protected userRequestHandlerTimeoutMillis: number;
420
+ protected preNavigationHooks: CheerioHook<JSONData>[];
421
+ protected postNavigationHooks: CheerioHook<JSONData>[];
422
+ protected persistCookiesPerSession: boolean;
423
+ protected requestTimeoutMillis: number;
424
+ protected ignoreSslErrors: boolean;
425
+ protected suggestResponseEncoding?: string;
426
+ protected forceResponseEncoding?: string;
427
+ protected readonly supportedMimeTypes: Set<string>;
428
+ protected static optionsShape: {
429
+ handlePageFunction: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
430
+ requestTimeoutSecs: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
431
+ ignoreSslErrors: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
432
+ additionalMimeTypes: import("ow").ArrayPredicate<string>;
433
+ suggestResponseEncoding: import("ow").StringPredicate & import("ow").BasePredicate<string | undefined>;
434
+ forceResponseEncoding: import("ow").StringPredicate & import("ow").BasePredicate<string | undefined>;
435
+ proxyConfiguration: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
436
+ persistCookiesPerSession: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
437
+ preNavigationHooks: import("ow").ArrayPredicate<unknown> & import("ow").BasePredicate<unknown[] | undefined>;
438
+ postNavigationHooks: import("ow").ArrayPredicate<unknown> & import("ow").BasePredicate<unknown[] | undefined>;
439
+ requestList: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
440
+ requestQueue: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
441
+ requestHandler: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
442
+ handleRequestFunction: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
443
+ requestHandlerTimeoutSecs: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
444
+ handleRequestTimeoutSecs: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>; /**
445
+ * An object with information about currently used proxy by the crawler
446
+ * and configured by the {@link ProxyConfiguration} class.
447
+ */
448
+ failedRequestHandler: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
449
+ handleFailedRequestFunction: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
450
+ maxRequestRetries: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
451
+ maxRequestsPerCrawl: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
452
+ autoscaledPoolOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
453
+ sessionPoolOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
454
+ useSessionPool: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
455
+ minConcurrency: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
456
+ maxConcurrency: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
457
+ log: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
458
+ };
459
+ /**
460
+ * All `CheerioCrawler` parameters are passed via an options object.
461
+ */
462
+ constructor(options: CheerioCrawlerOptions<JSONData>);
463
+ /**
464
+ * **EXPERIMENTAL**
465
+ * Function for attaching CrawlerExtensions such as the Unblockers.
466
+ * @param extension Crawler extension that overrides the crawler configuration.
467
+ */
468
+ use(extension: CrawlerExtension): void;
469
+ /**
470
+ * Wrapper around handlePageFunction that opens and closes pages etc.
471
+ */
472
+ protected _runRequestHandler(crawlingContext: CheerioCrawlingContext<JSONData>): Promise<void>;
473
+ protected _handleNavigation(crawlingContext: CheerioCrawlingContext<JSONData>): Promise<void>;
474
+ /**
475
+ * Sets the cookie header to `gotOptions` based on the provided request and session headers, as well as any changes that occurred due to hooks.
476
+ */
477
+ private _applyCookies;
478
+ /**
479
+ * Function to make the HTTP request. It performs optimizations
480
+ * on the request such as only downloading the request body if the
481
+ * received content type matches text/html, application/xml, application/xhtml+xml.
482
+ */
483
+ protected _requestFunction({ request, session, proxyUrl, gotOptions }: RequestFunctionOptions): Promise<IncomingMessage>;
484
+ /**
485
+ * Encodes and parses response according to the provided content type
486
+ */
487
+ protected _parseResponse(request: Request, responseStream: IncomingMessage): Promise<{
488
+ dom: unknown;
489
+ isXml: boolean;
490
+ response: IncomingMessage;
491
+ contentType: {
492
+ type: string;
493
+ encoding: BufferEncoding;
494
+ };
495
+ body?: undefined;
496
+ } | {
497
+ body: Buffer;
498
+ response: IncomingMessage;
499
+ contentType: {
500
+ type: string;
501
+ encoding: BufferEncoding;
502
+ };
503
+ dom?: undefined;
504
+ isXml?: undefined;
505
+ }>;
506
+ /**
507
+ * Combines the provided `requestOptions` with mandatory (non-overridable) values.
508
+ */
509
+ protected _getRequestOptions(request: Request, session?: Session, proxyUrl?: string, gotOptions?: OptionsInit): OptionsInit & {
510
+ isStream: true;
511
+ };
512
+ protected _encodeResponse(request: Request, response: IncomingMessage, encoding: BufferEncoding): {
513
+ encoding: BufferEncoding;
514
+ response: IncomingMessage;
515
+ };
516
+ protected _parseHtmlToDom(response: IncomingMessage): Promise<unknown>;
517
+ /**
518
+ * Checks and extends supported mime types
519
+ */
520
+ protected _extendSupportedMimeTypes(additionalMimeTypes: (string | RequestLike | ResponseLike)[]): void;
521
+ /**
522
+ * Handles timeout request
523
+ */
524
+ protected _handleRequestTimeout(session?: Session): void;
525
+ private _abortDownloadOfBody;
526
+ /**
527
+ * @internal wraps public utility for mocking purposes
528
+ */
529
+ private _requestAsBrowser;
530
+ }
531
+ interface EnqueueLinksInternalOptions {
532
+ options?: CheerioCrawlerEnqueueLinksOptions;
533
+ $: CheerioRoot | null;
534
+ requestQueue: RequestQueue;
535
+ originalRequestUrl: string;
536
+ finalRequestUrl?: string;
537
+ }
538
+ /** @internal */
539
+ export declare function cheerioCrawlerEnqueueLinks({ options, $, requestQueue, originalRequestUrl, finalRequestUrl }: EnqueueLinksInternalOptions): Promise<storage.BatchAddRequestsResult>;
540
+ interface RequestFunctionOptions {
541
+ request: Request;
542
+ session?: Session;
543
+ proxyUrl?: string;
544
+ gotOptions: OptionsInit;
545
+ }
546
+ export {};
547
+ //# sourceMappingURL=cheerio-crawler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cheerio-crawler.d.ts","sourceRoot":"","sources":["../../src/internals/cheerio-crawler.ts"],"names":[],"mappings":";AAEA,OAAO,EACH,YAAY,EACZ,mBAAmB,EAEtB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACH,gBAAgB,EAChB,+BAA+B,EAC/B,eAAe,EAEf,mBAAmB,EAEnB,kBAAkB,EAClB,SAAS,EACT,OAAO,EACP,YAAY,EAEZ,OAAO,EACP,OAAO,EAEV,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,UAAU,EAAyC,MAAM,gBAAgB,CAAC;AAE3G,OAA0B,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5E,OAAO,EAAe,WAAW,EAA+C,MAAM,cAAc,CAAC;AAGrG,OAAO,EAAuB,eAAe,EAAE,MAAM,MAAM,CAAC;AAoB5D,MAAM,WAAW,gCAAgC,C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