Skip to content

Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.

perf!: import only cheerio/slim in cheerio/http crawlers and utils (#4114)

Lukáš Křivka6864be3a8482
diff --git a/packages/cheerio-crawler/src/internals/cheerio-parser.ts b/packages/cheerio-crawler/src/internals/cheerio-parser.ts
index 24bac90a1..395c5b3f9 100644
--- a/packages/cheerio-crawler/src/internals/cheerio-parser.ts
+++ b/packages/cheerio-crawler/src/internals/cheerio-parser.ts
@@ -1,7 +1,8 @@
import type { DOMParser, InternalHttpCrawlingContext } from '@crawlee/http';
import { extractUrlsFromCheerio } from '@crawlee/utils/internal';
import type { CheerioAPI, CheerioOptions } from 'cheerio';
-import * as cheerio from 'cheerio';
+// slim uses faster htmlparser2 parser and doesn't load extra libs like undici
+import * as cheerio from 'cheerio/slim';
import { parseDocument } from 'htmlparser2';
export interface CheerioParseResult {
diff --git a/packages/http-crawler/src/internals/dom-crawler.ts b/packages/http-crawler/src/internals/dom-crawler.ts
index 274479bb0..6e0f4b243 100644
--- a/packages/http-crawler/src/internals/dom-crawler.ts
+++ b/packages/http-crawler/src/internals/dom-crawler.ts
@@ -277,7 +277,12 @@ export class DOMCrawler<
});
},
async parseWithCheerio(selector?: string, _timeoutMs = 5_000) {
- const $ = (await parser.toCheerio?.(context)) ?? (await import('cheerio')).load(context.body);
+ // Import full cheerio (not cheerio/slim) to be browser-compliant for DOM Crawlers (not CheerioCrawler).
+ const $ =
+ (await parser.toCheerio?.(context)) ??
+ (await import('cheerio')).load(context.body, {
+ xmlMode: context.contentType.type.includes('xml'),
+ });
if (selector && $(selector).get().length === 0) {
throw new Error(`Selector '${selector}' not found.`);
diff --git a/packages/http-crawler/src/internals/http-crawler.ts b/packages/http-crawler/src/internals/http-crawler.ts
index 2437e9947..275e63f97 100644
--- a/packages/http-crawler/src/internals/http-crawler.ts
+++ b/packages/http-crawler/src/internals/http-crawler.ts
@@ -613,17 +613,20 @@ export class HttpCrawler<
const response = parsed.response!;
const contentType = parsed.contentType!;
+ const loadBody = async () => {
+ const { load } = await import('cheerio/slim');
+
+ return load(parsed.body!.toString(), { xmlMode: contentType.type.includes('xml') });
+ };
const waitForSelector = async (selector: string, _timeoutMs?: number) => {
- const cheerio = await import('cheerio');
- const $ = cheerio.load(parsed.body!.toString());
+ const $ = await loadBody();
if ($(selector).get().length === 0) {
throw new Error(`Selector '${selector}' not found.`);
}
};
const parseWithCheerio = async (selector?: string, timeoutMs?: number) => {
- const cheerio = await import('cheerio');
- const $ = cheerio.load(parsed.body!.toString());
+ const $ = await loadBody();
if (selector) {
await (crawlingContext as InternalHttpCrawlingContext).waitForSelector(selector, timeoutMs);
diff --git a/packages/playwright-crawler/src/internals/utils/playwright-utils.ts b/packages/playwright-crawler/src/internals/utils/playwright-utils.ts
index 8e95548c2..e6efa2626 100644
--- a/packages/playwright-crawler/src/internals/utils/playwright-utils.ts
+++ b/packages/playwright-crawler/src/internals/utils/playwright-utils.ts
@@ -588,6 +588,7 @@ export async function parseWithCheerio(
? null
: ((await page.evaluate(`(${expandShadowRoots.toString()})(document)`)) as string);
const pageContent = html || (await page.content());
+ // Full cheerio (parse5) import for browser compliant parser
const { load } = await import('cheerio');
const $ = load(pageContent);
diff --git a/packages/puppeteer-crawler/src/internals/utils/puppeteer_utils.ts b/packages/puppeteer-crawler/src/internals/utils/puppeteer_utils.ts
index dfca18387..10a8975fa 100644
--- a/packages/puppeteer-crawler/src/internals/utils/puppeteer_utils.ts
+++ b/packages/puppeteer-crawler/src/internals/utils/puppeteer_utils.ts
@@ -263,6 +263,7 @@ export async function parseWithCheerio(
: ((await page.evaluate(`(${expandShadowRoots.toString()})(document)`)) as string);
const pageContent = html || (await page.content());
+ // Full cheerio (parse5) import for browser compliant parser
const { load } = await import('cheerio');
return load(pageContent);
}
diff --git a/packages/utils/src/internals/cheerio.ts b/packages/utils/src/internals/cheerio.ts
index 20f74819c..a88e4bf81 100644
--- a/packages/utils/src/internals/cheerio.ts
+++ b/packages/utils/src/internals/cheerio.ts
@@ -39,7 +39,7 @@ const BLOCK_TAGS_REGEX =
* @return Plain text
*/
export async function htmlToText(htmlOrCheerioElement: string | CheerioAPI): Promise<string> {
- const { load } = await import('cheerio');
+ const { load } = await import('cheerio/slim');
if (!htmlOrCheerioElement) return '';
@@ -53,8 +53,10 @@ export async function htmlToText(htmlOrCheerioElement: string | CheerioAPI): Pro
if (elem.type === 'text') {
// Compress spaces, unless we're inside <pre> element
let compr;
- if (elem.parent?.tagName === 'pre') compr = elem.data;
- else compr = elem.data.replace(/\s+/g, ' ');
+ if (elem.parent?.tagName === 'pre') {
+ // Strip single newline right after `<pre>` that htmlparser2 keeps
+ compr = elem.parent.children?.[0] === elem ? elem.data.replace(/^\r?\n/, '') : elem.data;
+ } else compr = elem.data.replace(/\s+/g, ' ');
// If text is empty or ends with a whitespace, don't add the leading whitespace
if (compr.startsWith(' ') && /(^|\s)$/.test(text)) compr = compr.substring(1);
text += compr;
diff --git a/packages/utils/src/internals/extract-microdata.ts b/packages/utils/src/internals/extract-microdata.ts
index a9b222196..ab2b2f4c3 100644
--- a/packages/utils/src/internals/extract-microdata.ts
+++ b/packages/utils/src/internals/extract-microdata.ts
@@ -35,7 +35,7 @@ export async function extractMicrodata(raw: string): Promise<MicrodataItem[]>;
export async function extractMicrodata($: CheerioAPI): Promise<MicrodataItem[]>;
export async function extractMicrodata(htmlOrCheerioElement: string | CheerioAPI): Promise<MicrodataItem[]> {
// Dynamic so that importing `@crawlee/utils` does not pull in cheerio - see #3836.
- const { load } = await import('cheerio');
+ const { load } = await import('cheerio/slim');
const $ = typeof htmlOrCheerioElement === 'string' ? load(htmlOrCheerioElement) : htmlOrCheerioElement;
const context: ExtractionContext = { $ };
diff --git a/packages/utils/src/internals/open_graph_parser.ts b/packages/utils/src/internals/open_graph_parser.ts
index 3290f6b79..1f5d15b1f 100644
--- a/packages/utils/src/internals/open_graph_parser.ts
+++ b/packages/utils/src/internals/open_graph_parser.ts
@@ -403,7 +403,7 @@ export async function parseOpenGraph(
additionalProperties?: OpenGraphProperty[],
): Promise<Dictionary<OpenGraphResult>>;
export async function parseOpenGraph(item: CheerioAPI | string, additionalProperties?: OpenGraphProperty[]) {
- const { load } = await import('cheerio');
+ const { load } = await import('cheerio/slim');
const $ = typeof item === 'string' ? load(item) : item;
return [...(additionalProperties || []), ...OPEN_GRAPH_PROPERTIES].reduce((acc, curr) => {
diff --git a/packages/utils/src/internals/social.ts b/packages/utils/src/internals/social.ts
index 9977d6504..9293934dc 100644
--- a/packages/utils/src/internals/social.ts
+++ b/packages/utils/src/internals/social.ts
@@ -663,7 +663,7 @@ export async function parseHandlesFromHtml(
html: string,
data: Record<string, unknown> | null = null,
): Promise<SocialHandles> {
- const cheerio = await import('cheerio');
+ const cheerio = await import('cheerio/slim');
const result: SocialHandles = {
emails: [],
diff --git a/test/core/crawlers/http_crawler.test.ts b/test/core/crawlers/http_crawler.test.ts
index 3e3b918d5..cd8aaedef 100644
--- a/test/core/crawlers/http_crawler.test.ts
+++ b/test/core/crawlers/http_crawler.test.ts
@@ -31,6 +31,16 @@ router.set('/noext', (req, res) => {
res.end(`<html><head><title>Example Domain</title></head></html>`);
});
+router.set('/feed.xml', (req, res) => {
+ res.setHeader('content-type', 'application/rss+xml; charset=utf-8');
+ res.end(
+ `<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"><channel>` +
+ `<item><title>Post one</title><link>https://example.com/one</link></item>` +
+ `<item><title>Post two</title><link>https://example.com/two</link></item>` +
+ `</channel></rss>`,
+ );
+});
+
router.set('/invalidContentType', (req, res) => {
res.setHeader('content-type', 'crazy-stuff; charset=utf-8');
res.end(`<html><head><title>Example Domain</title></head></html>`);
@@ -222,6 +232,29 @@ test('parseWithCheerio works', async () => {
expect(results).toStrictEqual(['Example Domain']);
});
+// `<link>` is a void element in HTML, so an HTML parser drops its content - the XML feeds that
+// `HttpCrawler` also serves have to be parsed in xml mode to survive.
+test('parseWithCheerio parses XML responses as XML', async () => {
+ const results: string[][] = [];
+
+ const crawler = new HttpCrawler({
+ maxRequestRetries: 0,
+ additionalMimeTypes: ['application/rss+xml'],
+ requestHandler: async ({ parseWithCheerio }) => {
+ const $ = await parseWithCheerio();
+ results.push(
+ $('item > link')
+ .map((_i, el) => $(el).text())
+ .get(),
+ );
+ },
+ });
+
+ await crawler.run([`${url}/feed.xml`]);
+
+ expect(results).toStrictEqual([['https://example.com/one', 'https://example.com/two']]);
+});
+
test('should parse content type from header', async () => {
const results: { type: string; encoding: BufferEncoding }[] = [];