@crawlee/cheerio 4.0.0-beta.34 → 4.0.0-beta.341

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 CHANGED
@@ -1,23 +1,23 @@
1
1
  <h1 align="center">
2
2
  <a href="https://crawlee.dev">
3
3
  <picture>
4
- <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-dark.svg?sanitize=true">
5
- <img alt="Crawlee" src="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-light.svg?sanitize=true" width="500">
4
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-dark.svg?sanitize=true" />
5
+ <img alt="Crawlee" src="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-light.svg?sanitize=true" width="500" />
6
6
  </picture>
7
7
  </a>
8
- <br>
8
+ <br />
9
9
  <small>A web scraping and browser automation library</small>
10
10
  </h1>
11
11
 
12
- <p align=center>
13
- <a href="https://trendshift.io/repositories/5179" target="_blank"><img src="https://trendshift.io/api/badge/repositories/5179" alt="apify%2Fcrawlee | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
12
+ <p align="center">
13
+ <a href="https://trendshift.io/repositories/5179" target="_blank"><img src="https://trendshift.io/api/badge/repositories/5179" alt="apify%2Fcrawlee | Trendshift" width="250" height="55"/></a>
14
14
  </p>
15
15
 
16
- <p align=center>
17
- <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/v/@crawlee/core.svg" alt="NPM latest version" data-canonical-src="https://img.shields.io/npm/v/@crawlee/core/next.svg" style="max-width: 100%;"></a>
18
- <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/dm/@crawlee/core.svg" alt="Downloads" data-canonical-src="https://img.shields.io/npm/dm/@crawlee/core.svg" style="max-width: 100%;"></a>
19
- <a href="https://discord.gg/jyEM2PRvMU" rel="nofollow"><img src="https://img.shields.io/discord/801163717915574323?label=discord" alt="Chat on discord" data-canonical-src="https://img.shields.io/discord/801163717915574323?label=discord" style="max-width: 100%;"></a>
20
- <a href="https://github.com/apify/crawlee/actions/workflows/test-ci.yml"><img src="https://github.com/apify/crawlee/actions/workflows/test-ci.yml/badge.svg?branch=master" alt="Build Status" style="max-width: 100%;"></a>
16
+ <p align="center">
17
+ <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/v/@crawlee/core.svg" alt="NPM latest version" data-canonical-src="https://img.shields.io/npm/v/@crawlee/core/next.svg" /></a>
18
+ <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/dm/@crawlee/core.svg" alt="Downloads" data-canonical-src="https://img.shields.io/npm/dm/@crawlee/core.svg" /></a>
19
+ <a href="https://discord.gg/jyEM2PRvMU" rel="nofollow"><img src="https://img.shields.io/discord/801163717915574323?label=discord" alt="Chat on discord" data-canonical-src="https://img.shields.io/discord/801163717915574323?label=discord" /></a>
20
+ <a href="https://github.com/apify/crawlee/actions/workflows/test-ci.yml"><img src="https://github.com/apify/crawlee/actions/workflows/test-ci.yml/badge.svg?branch=master" alt="Build Status" /></a>
21
21
  </p>
22
22
 
23
23
  Crawlee covers your crawling and scraping end-to-end and **helps you build reliable scrapers. Fast.**
@@ -34,7 +34,7 @@ Crawlee is available as the [`crawlee`](https://www.npmjs.com/package/crawlee) N
34
34
 
35
35
  We recommend visiting the [Introduction tutorial](https://crawlee.dev/js/docs/introduction) in Crawlee documentation for more information.
36
36
 
37
- > Crawlee requires **Node.js 16 or higher**.
37
+ > Crawlee requires **Node.js 22.13 or higher**.
38
38
 
39
39
  ### With Crawlee CLI
40
40
 
@@ -144,6 +144,10 @@ Crawlee is open-source and runs anywhere, but since it's developed by [Apify](ht
144
144
 
145
145
  If you find any bug or issue with Crawlee, please [submit an issue on GitHub](https://github.com/apify/crawlee/issues). For questions, you can ask on [Stack Overflow](https://stackoverflow.com/questions/tagged/apify), in GitHub Discussions or you can join our [Discord server](https://discord.com/invite/jyEM2PRvMU).
146
146
 
147
+ ## Supported versions
148
+
149
+ New features and bug fixes land in the latest major version. The previous major version keeps receiving fixes for high and critical severity vulnerabilities for 12 months after the next major is released, and reaches end of life after that. See the [security policy](https://github.com/apify/crawlee/security/policy) for the current status of each version and for how to report a vulnerability.
150
+
147
151
  ## Contributing
148
152
 
149
153
  Your code contributions are welcome, and you'll be praised to eternity! If you have any ideas for improvements, either submit an issue or create a pull request. For contribution guidelines and the code of conduct, see [CONTRIBUTING.md](https://github.com/apify/crawlee/blob/master/CONTRIBUTING.md).
package/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  export * from '@crawlee/http';
2
2
  export * from './internals/cheerio-crawler.js';
3
- //# sourceMappingURL=index.d.ts.map
3
+ export type { CheerioParseResult } from './internals/cheerio-parser.js';
package/index.js CHANGED
@@ -1,3 +1,2 @@
1
1
  export * from '@crawlee/http';
2
2
  export * from './internals/cheerio-crawler.js';
3
- //# sourceMappingURL=index.js.map
@@ -1,59 +1,18 @@
1
- import type { BasicCrawlingContext, EnqueueLinksOptions, ErrorHandler, GetUserDataFromRequest, HttpCrawlerOptions, InternalHttpCrawlingContext, InternalHttpHook, RequestHandler, RequestProvider, RouterRoutes, SkippedRequestCallback } from '@crawlee/http';
2
- import { HttpCrawler } from '@crawlee/http';
3
- import type { BatchAddRequestsResult, Dictionary } from '@crawlee/types';
4
- import { type CheerioRoot, type RobotsTxtFile } from '@crawlee/utils';
5
- import type { CheerioAPI } from 'cheerio';
6
- import * as cheerio from 'cheerio';
1
+ import type { CrawlingContext, DOMCrawlingContext, ErrorHandler, GetUserDataFromRequest, HttpCrawlerOptions, RequestHandler, RouterHandler, RouterRoutes, RouteSchemas, RoutesFromSchemas } from '@crawlee/http';
2
+ import { DOMCrawler } from '@crawlee/http';
3
+ import type { Dictionary } from '@crawlee/types';
4
+ import type { Cheerio } from 'cheerio';
5
+ import type { AnyNode } from 'domhandler';
6
+ import type { CheerioParseResult } from './cheerio-parser.js';
7
7
  export type CheerioErrorHandler<UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
8
- JSONData extends Dictionary = any> = ErrorHandler<CheerioCrawlingContext<UserData, JSONData>>;
8
+ JSONData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
9
+ ContextExtension = Dictionary<never>> = ErrorHandler<CrawlingContext, CheerioCrawlingContext<UserData, JSONData> & ContextExtension>;
9
10
  export interface CheerioCrawlerOptions<ContextExtension = Dictionary<never>, ExtendedContext extends CheerioCrawlingContext = CheerioCrawlingContext & ContextExtension, UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
10
- JSONData extends Dictionary = any> extends HttpCrawlerOptions<CheerioCrawlingContext<UserData, JSONData>, ContextExtension, ExtendedContext> {
11
+ JSONData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
12
+ Routes extends Record<keyof Routes, Dictionary> = Record<string, UserData>, StatisticStateExtension extends object = {}> extends Omit<HttpCrawlerOptions<CheerioCrawlingContext<UserData, JSONData>, ContextExtension, ExtendedContext, Routes, StatisticStateExtension>, 'contextPipelineBuilder'> {
11
13
  }
12
- export type CheerioHook<UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
13
- JSONData extends Dictionary = any> = InternalHttpHook<CheerioCrawlingContext<UserData, JSONData>>;
14
14
  export interface CheerioCrawlingContext<UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
15
- JSONData extends Dictionary = any> extends InternalHttpCrawlingContext<UserData, JSONData> {
16
- /**
17
- * The raw HTML content of the web page as a string.
18
- */
19
- body: string;
20
- /**
21
- * The [Cheerio](https://cheerio.js.org/) object with parsed HTML.
22
- * Cheerio is available only for HTML and XML content types.
23
- */
24
- $: cheerio.CheerioAPI;
25
- /**
26
- * Wait for an element matching the selector to appear. Timeout is ignored.
27
- *
28
- * **Example usage:**
29
- * ```ts
30
- * async requestHandler({ waitForSelector, parseWithCheerio }) {
31
- * await waitForSelector('article h1');
32
- * const $ = await parseWithCheerio();
33
- * const title = $('title').text();
34
- * });
35
- * ```
36
- */
37
- waitForSelector(selector: string, timeoutMs?: number): Promise<void>;
38
- /**
39
- * Returns Cheerio handle, this is here to unify the crawler API, so they all have this handy method.
40
- * It has the same return type as the `$` context property, use it only if you are abstracting your workflow to
41
- * support different context types in one handler.
42
- * When provided with the `selector` argument, it will throw if it's not available.
43
- *
44
- * **Example usage:**
45
- * ```ts
46
- * async requestHandler({ parseWithCheerio }) {
47
- * const $ = await parseWithCheerio();
48
- * const title = $('title').text();
49
- * });
50
- * ```
51
- */
52
- parseWithCheerio(selector?: string, timeoutMs?: number): Promise<CheerioRoot>;
53
- /**
54
- * Helper function for extracting URLs from the parsed HTML and adding them to the request queue.
55
- */
56
- enqueueLinks(options?: EnqueueLinksOptions): Promise<BatchAddRequestsResult>;
15
+ JSONData extends Dictionary = any> extends DOMCrawlingContext<CheerioParseResult, Cheerio<AnyNode>, Cheerio<AnyNode>, UserData, JSONData> {
57
16
  }
58
17
  export type CheerioRequestHandler<UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
59
18
  JSONData extends Dictionary = any> = RequestHandler<CheerioCrawlingContext<UserData, JSONData>>;
@@ -73,13 +32,15 @@ JSONData extends Dictionary = any> = RequestHandler<CheerioCrawlingContext<UserD
73
32
  * and then invokes the user-provided {@link CheerioCrawlerOptions.requestHandler} to extract page data
74
33
  * using a [jQuery](https://jquery.com/)-like interface to the parsed HTML DOM.
75
34
  *
76
- * The source URLs are represented using {@link Request} objects that are fed from
77
- * {@link RequestList} or {@link RequestQueue} instances provided by the {@link CheerioCrawlerOptions.requestList}
78
- * or {@link CheerioCrawlerOptions.requestQueue} constructor options, respectively.
35
+ * The source URLs are represented using {@link Request} objects that are fed from the
36
+ * {@link IRequestManager|request manager} provided via the {@link CheerioCrawlerOptions.requestManager|`requestManager`}
37
+ * constructor option (a {@link RequestQueue} is itself a request manager). To read from a read-only source such
38
+ * as a {@link RequestList} while still being able to enqueue new requests, combine it with a queue into a
39
+ * {@link RequestManagerTandem} via {@link IRequestLoader.toTandem|`requestLoader.toTandem()`} and pass the
40
+ * result as `requestManager`.
79
41
  *
80
- * If both {@link CheerioCrawlerOptions.requestList} and {@link CheerioCrawlerOptions.requestQueue} are used,
81
- * the instance first processes URLs from the {@link RequestList} and automatically enqueues all of them
82
- * to {@link RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.
42
+ * > The {@link CheerioCrawlerOptions.requestList|`requestList`} and {@link CheerioCrawlerOptions.requestQueue|`requestQueue`}
43
+ * > options are deprecated; they are still accepted and folded into a single `requestManager` for back-compat.
83
44
  *
84
45
  * The crawler finishes when there are no more {@link Request} objects to crawl.
85
46
  *
@@ -100,11 +61,11 @@ JSONData extends Dictionary = any> = RequestHandler<CheerioCrawlingContext<UserD
100
61
  * Beware that the parsing behavior differs for HTML, XML, JSON and other types of content.
101
62
  * For more details, see {@link CheerioCrawlerOptions.requestHandler}.
102
63
  *
103
- * New requests are only dispatched when there is enough free CPU and memory available,
104
- * using the functionality provided by the {@link AutoscaledPool} class.
105
- * All {@link AutoscaledPool} configuration options can be passed to the `autoscaledPoolOptions`
106
- * parameter of the `CheerioCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency`
107
- * {@link AutoscaledPool} options are available directly in the `CheerioCrawler` constructor.
64
+ * New requests are only dispatched when there is enough free CPU and memory available, as judged by the crawler's
65
+ * {@link ConcurrencySystem}.
66
+ * Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the
67
+ * `CheerioCrawler` constructor, or, for finer control, by injecting a pre-configured
68
+ * {@link ConcurrencySystem|`concurrencySystem`}.
108
69
  *
109
70
  * **Example usage:**
110
71
  *
@@ -134,41 +95,12 @@ JSONData extends Dictionary = any> = RequestHandler<CheerioCrawlingContext<UserD
134
95
  * ```
135
96
  * @category Crawlers
136
97
  */
137
- export declare class CheerioCrawler<ContextExtension = Dictionary<never>, ExtendedContext extends CheerioCrawlingContext = CheerioCrawlingContext & ContextExtension> extends HttpCrawler<CheerioCrawlingContext, ContextExtension, ExtendedContext> {
98
+ export declare class CheerioCrawler<ContextExtension = Dictionary<never>, ExtendedContext extends CheerioCrawlingContext = CheerioCrawlingContext & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<CheerioCrawlingContext['request']>>, StatisticStateExtension extends object = {}> extends DOMCrawler<CheerioParseResult, Cheerio<AnyNode>, Cheerio<AnyNode>, ContextExtension, ExtendedContext, Routes, StatisticStateExtension> {
138
99
  /**
139
100
  * All `CheerioCrawler` parameters are passed via an options object.
140
101
  */
141
- constructor(options?: CheerioCrawlerOptions<ContextExtension, ExtendedContext>);
142
- // @ts-ignore optional peer dependency or compatibility with es2022
143
- protected buildContextPipeline(): import("@crawlee/http").ContextPipeline<import("@crawlee/http").CrawlingContext<Dictionary>, InternalHttpCrawlingContext<any, any> & {
144
- $: CheerioAPI;
145
- body: string;
146
- } & {
147
- enqueueLinks: (enqueueOptions?: EnqueueLinksOptions) => Promise<BatchAddRequestsResult>;
148
- waitForSelector: (selector: string, _timeoutMs?: number) => Promise<void>;
149
- parseWithCheerio: (selector?: string, timeoutMs?: number) => Promise<CheerioAPI>;
150
- }>;
151
- private parseContent;
152
- private addHelpers;
153
- }
154
- interface EnqueueLinksInternalOptions {
155
- options?: EnqueueLinksOptions;
156
- $: cheerio.CheerioAPI | null;
157
- requestQueue: RequestProvider;
158
- robotsTxtFile?: RobotsTxtFile;
159
- onSkippedRequest?: SkippedRequestCallback;
160
- originalRequestUrl: string;
161
- finalRequestUrl?: string;
162
- }
163
- interface BoundEnqueueLinksInternalOptions {
164
- enqueueLinks: BasicCrawlingContext['enqueueLinks'];
165
- options?: EnqueueLinksOptions;
166
- $: cheerio.CheerioAPI | null;
167
- originalRequestUrl: string;
168
- finalRequestUrl?: string;
102
+ constructor(options?: CheerioCrawlerOptions<ContextExtension, ExtendedContext, any, any, Routes, StatisticStateExtension>);
169
103
  }
170
- /** @internal */
171
- export declare function cheerioCrawlerEnqueueLinks(options: EnqueueLinksInternalOptions | BoundEnqueueLinksInternalOptions): Promise<unknown>;
172
104
  /**
173
105
  * Creates new {@link Router} instance that works based on request labels.
174
106
  * This instance can then serve as a `requestHandler` of your {@link CheerioCrawler}.
@@ -193,7 +125,6 @@ export declare function cheerioCrawlerEnqueueLinks(options: EnqueueLinksInternal
193
125
  * await crawler.run();
194
126
  * ```
195
127
  */
196
- // @ts-ignore optional peer dependency or compatibility with es2022
197
- export declare function createCheerioRouter<Context extends CheerioCrawlingContext = CheerioCrawlingContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, UserData>): import("@crawlee/http").RouterHandler<Context>;
198
- export {};
199
- //# sourceMappingURL=cheerio-crawler.d.ts.map
128
+ export declare function createCheerioRouter<Context extends CheerioCrawlingContext = CheerioCrawlingContext, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<Context['request']>>>(routes?: RouterRoutes<Context, Routes>): RouterHandler<Context, Routes>;
129
+ export declare function createCheerioRouter<Context extends CheerioCrawlingContext = CheerioCrawlingContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, Record<string, UserData>>): RouterHandler<Context, Record<string, UserData>>;
130
+ export declare function createCheerioRouter<Context extends CheerioCrawlingContext = CheerioCrawlingContext, const Schemas extends RouteSchemas = RouteSchemas>(schemas: Schemas): RouterHandler<Context, RoutesFromSchemas<Schemas>>;
@@ -1,7 +1,5 @@
1
- import { enqueueLinks, HttpCrawler, resolveBaseUrlForEnqueueLinksFiltering, Router } from '@crawlee/http';
2
- import { extractUrlsFromCheerio } from '@crawlee/utils';
3
- import * as cheerio from 'cheerio';
4
- import { parseDocument } from 'htmlparser2';
1
+ import { DOMCrawler, Router } from '@crawlee/http';
2
+ import { cheerioParser } from './cheerio-parser.js';
5
3
  /**
6
4
  * Provides a framework for the parallel crawling of web pages using plain HTTP requests and
7
5
  * [cheerio](https://www.npmjs.com/package/cheerio) HTML parser.
@@ -18,13 +16,15 @@ import { parseDocument } from 'htmlparser2';
18
16
  * and then invokes the user-provided {@link CheerioCrawlerOptions.requestHandler} to extract page data
19
17
  * using a [jQuery](https://jquery.com/)-like interface to the parsed HTML DOM.
20
18
  *
21
- * The source URLs are represented using {@link Request} objects that are fed from
22
- * {@link RequestList} or {@link RequestQueue} instances provided by the {@link CheerioCrawlerOptions.requestList}
23
- * or {@link CheerioCrawlerOptions.requestQueue} constructor options, respectively.
19
+ * The source URLs are represented using {@link Request} objects that are fed from the
20
+ * {@link IRequestManager|request manager} provided via the {@link CheerioCrawlerOptions.requestManager|`requestManager`}
21
+ * constructor option (a {@link RequestQueue} is itself a request manager). To read from a read-only source such
22
+ * as a {@link RequestList} while still being able to enqueue new requests, combine it with a queue into a
23
+ * {@link RequestManagerTandem} via {@link IRequestLoader.toTandem|`requestLoader.toTandem()`} and pass the
24
+ * result as `requestManager`.
24
25
  *
25
- * If both {@link CheerioCrawlerOptions.requestList} and {@link CheerioCrawlerOptions.requestQueue} are used,
26
- * the instance first processes URLs from the {@link RequestList} and automatically enqueues all of them
27
- * to {@link RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.
26
+ * > The {@link CheerioCrawlerOptions.requestList|`requestList`} and {@link CheerioCrawlerOptions.requestQueue|`requestQueue`}
27
+ * > options are deprecated; they are still accepted and folded into a single `requestManager` for back-compat.
28
28
  *
29
29
  * The crawler finishes when there are no more {@link Request} objects to crawl.
30
30
  *
@@ -45,11 +45,11 @@ import { parseDocument } from 'htmlparser2';
45
45
  * Beware that the parsing behavior differs for HTML, XML, JSON and other types of content.
46
46
  * For more details, see {@link CheerioCrawlerOptions.requestHandler}.
47
47
  *
48
- * New requests are only dispatched when there is enough free CPU and memory available,
49
- * using the functionality provided by the {@link AutoscaledPool} class.
50
- * All {@link AutoscaledPool} configuration options can be passed to the `autoscaledPoolOptions`
51
- * parameter of the `CheerioCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency`
52
- * {@link AutoscaledPool} options are available directly in the `CheerioCrawler` constructor.
48
+ * New requests are only dispatched when there is enough free CPU and memory available, as judged by the crawler's
49
+ * {@link ConcurrencySystem}.
50
+ * Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the
51
+ * `CheerioCrawler` constructor, or, for finer control, by injecting a pre-configured
52
+ * {@link ConcurrencySystem|`concurrencySystem`}.
53
53
  *
54
54
  * **Example usage:**
55
55
  *
@@ -79,126 +79,14 @@ import { parseDocument } from 'htmlparser2';
79
79
  * ```
80
80
  * @category Crawlers
81
81
  */
82
- export class CheerioCrawler extends HttpCrawler {
82
+ export class CheerioCrawler extends DOMCrawler {
83
83
  /**
84
84
  * All `CheerioCrawler` parameters are passed via an options object.
85
85
  */
86
86
  constructor(options) {
87
- const { contextPipelineBuilder, ...rest } = options ?? {};
88
- super({
89
- ...rest,
90
- contextPipelineBuilder: contextPipelineBuilder ?? (() => this.buildContextPipeline()),
91
- });
92
- }
93
- buildContextPipeline() {
94
- return super
95
- .buildContextPipeline()
96
- .compose({
97
- action: async (context) => await this.parseContent(context),
98
- })
99
- .compose({ action: async (context) => await this.addHelpers(context) });
100
- }
101
- async parseContent(crawlingContext) {
102
- const isXml = crawlingContext.contentType.type.includes('xml');
103
- const body = Buffer.isBuffer(crawlingContext.body)
104
- ? crawlingContext.body.toString(crawlingContext.contentType.encoding)
105
- : crawlingContext.body;
106
- const dom = parseDocument(body, { decodeEntities: true, xmlMode: isXml });
107
- const $ = cheerio.load(dom, {
108
- xml: { decodeEntities: true, xmlMode: isXml },
109
- });
110
- return {
111
- $,
112
- body,
113
- };
114
- }
115
- async addHelpers(crawlingContext) {
116
- const originalEnqueueLinks = crawlingContext.enqueueLinks;
117
- return {
118
- enqueueLinks: async (enqueueOptions) => {
119
- return (await cheerioCrawlerEnqueueLinks({
120
- options: { ...enqueueOptions, limit: this.calculateEnqueuedRequestLimit(enqueueOptions?.limit) },
121
- $: crawlingContext.$,
122
- requestQueue: await this.getRequestQueue(),
123
- robotsTxtFile: await this.getRobotsTxtFileForUrl(crawlingContext.request.url),
124
- onSkippedRequest: this.handleSkippedRequest,
125
- originalRequestUrl: crawlingContext.request.url,
126
- finalRequestUrl: crawlingContext.request.loadedUrl,
127
- enqueueLinks: originalEnqueueLinks,
128
- })); // TODO make this type safe
129
- },
130
- waitForSelector: async (selector, _timeoutMs) => {
131
- if (crawlingContext.$(selector).get().length === 0) {
132
- throw new Error(`Selector '${selector}' not found.`);
133
- }
134
- },
135
- parseWithCheerio: async (selector, timeoutMs) => {
136
- if (selector) {
137
- await crawlingContext.waitForSelector(selector, timeoutMs);
138
- }
139
- return crawlingContext.$;
140
- },
141
- };
87
+ super({ ...options, parser: cheerioParser() });
142
88
  }
143
89
  }
144
- /** @internal */
145
- function containsEnqueueLinks(options) {
146
- return !!options.enqueueLinks;
147
- }
148
- /** @internal */
149
- export async function cheerioCrawlerEnqueueLinks(options) {
150
- const { options: enqueueLinksOptions, $, originalRequestUrl, finalRequestUrl } = options;
151
- if (!$) {
152
- throw new Error('Cannot enqueue links because the DOM is not available.');
153
- }
154
- const baseUrl = resolveBaseUrlForEnqueueLinksFiltering({
155
- enqueueStrategy: enqueueLinksOptions?.strategy,
156
- finalRequestUrl,
157
- originalRequestUrl,
158
- userProvidedBaseUrl: enqueueLinksOptions?.baseUrl,
159
- });
160
- const urls = extractUrlsFromCheerio($, enqueueLinksOptions?.selector ?? 'a', enqueueLinksOptions?.baseUrl ?? finalRequestUrl ?? originalRequestUrl);
161
- if (containsEnqueueLinks(options)) {
162
- return options.enqueueLinks({
163
- urls,
164
- baseUrl,
165
- ...enqueueLinksOptions,
166
- });
167
- }
168
- return enqueueLinks({
169
- requestQueue: options.requestQueue,
170
- robotsTxtFile: options.robotsTxtFile,
171
- onSkippedRequest: options.onSkippedRequest,
172
- urls,
173
- baseUrl,
174
- ...enqueueLinksOptions,
175
- });
176
- }
177
- /**
178
- * Creates new {@link Router} instance that works based on request labels.
179
- * This instance can then serve as a `requestHandler` of your {@link CheerioCrawler}.
180
- * Defaults to the {@link CheerioCrawlingContext}.
181
- *
182
- * > Serves as a shortcut for using `Router.create<CheerioCrawlingContext>()`.
183
- *
184
- * ```ts
185
- * import { CheerioCrawler, createCheerioRouter } from 'crawlee';
186
- *
187
- * const router = createCheerioRouter();
188
- * router.addHandler('label-a', async (ctx) => {
189
- * ctx.log.info('...');
190
- * });
191
- * router.addDefaultHandler(async (ctx) => {
192
- * ctx.log.info('...');
193
- * });
194
- *
195
- * const crawler = new CheerioCrawler({
196
- * requestHandler: router,
197
- * });
198
- * await crawler.run();
199
- * ```
200
- */
201
- export function createCheerioRouter(routes) {
202
- return Router.create(routes);
90
+ export function createCheerioRouter(routesOrSchemas) {
91
+ return Router.create(routesOrSchemas);
203
92
  }
204
- //# sourceMappingURL=cheerio-crawler.js.map
@@ -0,0 +1,12 @@
1
+ import type { DOMParser } from '@crawlee/http';
2
+ import type { Cheerio, CheerioAPI } from 'cheerio';
3
+ import type { AnyNode } from 'domhandler';
4
+ export interface CheerioParseResult {
5
+ $: CheerioAPI;
6
+ body: string;
7
+ }
8
+ /**
9
+ * A {@link DOMParser} backed by [cheerio](https://www.npmjs.com/package/cheerio). Pass it to a
10
+ * {@link DOMCrawler} to get the crawling context {@link CheerioCrawler} provides.
11
+ */
12
+ export declare function cheerioParser(): DOMParser<CheerioParseResult, Cheerio<AnyNode>, Cheerio<AnyNode>>;
@@ -0,0 +1,31 @@
1
+ import { extractUrlsFromCheerio } from '@crawlee/utils/internal';
2
+ // slim uses faster htmlparser2 parser and doesn't load extra libs like undici
3
+ import * as cheerio from 'cheerio/slim';
4
+ import { parseDocument } from 'htmlparser2';
5
+ /**
6
+ * A {@link DOMParser} backed by [cheerio](https://www.npmjs.com/package/cheerio). Pass it to a
7
+ * {@link DOMCrawler} to get the crawling context {@link CheerioCrawler} provides.
8
+ */
9
+ export function cheerioParser() {
10
+ return {
11
+ placeholderMembers: { $: true, body: true },
12
+ parse(context) {
13
+ const isXml = context.contentType.type.includes('xml');
14
+ const body = Buffer.isBuffer(context.body)
15
+ ? context.body.toString(context.contentType.encoding)
16
+ : context.body;
17
+ const dom = parseDocument(body, { decodeEntities: true, xmlMode: isXml });
18
+ const $ = cheerio.load(dom, {
19
+ xml: { decodeEntities: true, xmlMode: isXml },
20
+ });
21
+ return { $, body };
22
+ },
23
+ extractLinks: ({ $ }, selector, baseUrl) => extractUrlsFromCheerio($, selector, baseUrl),
24
+ querySelectorAll: ({ $ }, selector) => $(selector),
25
+ querySelectorOne: ({ $ }, selector) => {
26
+ const match = $(selector).first();
27
+ return match.length ? match : undefined;
28
+ },
29
+ toCheerio: ({ $ }) => $,
30
+ };
31
+ }
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@crawlee/cheerio",
3
- "version": "4.0.0-beta.34",
3
+ "version": "4.0.0-beta.341",
4
4
  "description": "The scalable web crawling and scraping library for JavaScript/Node.js. Enables development of data extraction and web automation jobs (not only) with headless Chrome and Puppeteer.",
5
5
  "engines": {
6
- "node": ">=22.0.0"
6
+ "node": ">=22.13.0"
7
7
  },
8
8
  "type": "module",
9
9
  "exports": {
@@ -38,7 +38,7 @@
38
38
  },
39
39
  "homepage": "https://crawlee.dev",
40
40
  "scripts": {
41
- "build": "yarn clean && yarn compile && yarn copy",
41
+ "build": "pnpm clean && pnpm compile && pnpm copy",
42
42
  "clean": "rimraf ./dist",
43
43
  "compile": "tsc -p tsconfig.build.json",
44
44
  "copy": "tsx ../../scripts/copy.ts"
@@ -47,12 +47,13 @@
47
47
  "access": "public"
48
48
  },
49
49
  "dependencies": {
50
- "@crawlee/http": "4.0.0-beta.34",
51
- "@crawlee/types": "4.0.0-beta.34",
52
- "@crawlee/utils": "4.0.0-beta.34",
53
- "cheerio": "^1.0.0",
54
- "htmlparser2": "^10.0.0",
55
- "tslib": "^2.8.1"
50
+ "@crawlee/http": "4.0.0-beta.341",
51
+ "@crawlee/types": "4.0.0-beta.341",
52
+ "@crawlee/utils": "4.0.0-beta.341",
53
+ "cheerio": "^1.2.0",
54
+ "domhandler": "^6.0.1",
55
+ "htmlparser2": "^10.1.0",
56
+ "tslib": "^2.9.1"
56
57
  },
57
58
  "lerna": {
58
59
  "command": {
@@ -61,5 +62,5 @@
61
62
  }
62
63
  }
63
64
  },
64
- "gitHead": "47c518d8d59f4e593d4b04e47537c3c847bbabb0"
65
+ "gitHead": "146b6d8aa25332881dc59d46d21b5bb1bf7673b1"
65
66
  }
package/index.d.ts.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,eAAe,CAAC;AAC9B,cAAc,gCAAgC,CAAC"}
package/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,eAAe,CAAC;AAC9B,cAAc,gCAAgC,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"cheerio-crawler.d.ts","sourceRoot":"","sources":["../../src/internals/cheerio-crawler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACR,oBAAoB,EACpB,mBAAmB,EACnB,YAAY,EACZ,sBAAsB,EACtB,kBAAkB,EAClB,2BAA2B,EAC3B,gBAAgB,EAChB,cAAc,EACd,eAAe,EACf,YAAY,EACZ,sBAAsB,EACzB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAgB,WAAW,EAAkD,MAAM,eAAe,CAAC;AAC1G,OAAO,KAAK,EAAE,sBAAsB,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AACzE,OAAO,EAAE,KAAK,WAAW,EAA0B,KAAK,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC9F,OAAO,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