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.

feat: http-crawler (#1440)

Szymon Marczak8c303f7fd718
diff --git a/docs/examples/cheerio_crawler.ts b/docs/examples/cheerio_crawler.ts
index 21fa67acf..c496c1572 100644
--- a/docs/examples/cheerio_crawler.ts
+++ b/docs/examples/cheerio_crawler.ts
@@ -57,6 +57,8 @@ const crawler = new CheerioCrawler({
});
// Run the crawler and wait for it to finish.
-await crawler.run();
+await crawler.run([
+ 'https://crawlee.dev',
+]);
log.debug('Crawler finished.');
diff --git a/docs/examples/http_crawler.mdx b/docs/examples/http_crawler.mdx
new file mode 100644
index 000000000..4c596cf6e
--- /dev/null
+++ b/docs/examples/http_crawler.mdx
@@ -0,0 +1,14 @@
+---
+id: http-crawler
+title: HTTP crawler
+---
+
+import CodeBlock from '@theme/CodeBlock';
+import ApiLink from '@site/src/components/ApiLink';
+import HttpCrawlerSource from '!!raw-loader!./http_crawler.ts';
+
+This example demonstrates how to use <ApiLink to="http-crawler/class/HttpCrawler">`HttpCrawler`</ApiLink> to crawl a list of URLs from an external file, load each URL using a plain HTTP request, and save HTML.
+
+<CodeBlock className="language-js">
+ {HttpCrawlerSource}
+</CodeBlock>
diff --git a/docs/examples/http_crawler.ts b/docs/examples/http_crawler.ts
new file mode 100644
index 000000000..4052df131
--- /dev/null
+++ b/docs/examples/http_crawler.ts
@@ -0,0 +1,54 @@
+import { Dataset, HttpCrawler, log, LogLevel } from 'crawlee';
+
+// Crawlers come with various utilities, e.g. for logging.
+// Here we use debug level of logging to improve the debugging experience.
+// This functionality is optional!
+log.setLevel(LogLevel.DEBUG);
+
+// Create an instance of the HttpCrawler class - a crawler
+// that automatically loads the URLs and saves their HTML.
+const crawler = new HttpCrawler({
+ // The crawler downloads and processes the web pages in parallel, with a concurrency
+ // automatically managed based on the available system memory and CPU (see AutoscaledPool class).
+ // Here we define some hard limits for the concurrency.
+ minConcurrency: 10,
+ maxConcurrency: 50,
+
+ // On error, retry each page at most once.
+ maxRequestRetries: 1,
+
+ // Increase the timeout for processing of each page.
+ requestHandlerTimeoutSecs: 30,
+
+ // Limit to 10 requests per one crawl
+ maxRequestsPerCrawl: 10,
+
+ // This function will be called for each URL to crawl.
+ // It accepts a single parameter, which is an object with options as:
+ // https://crawlee.dev/api/http-crawler/interface/HttpCrawlerOptions#requestHandler
+ // We use for demonstration only 2 of them:
+ // - request: an instance of the Request class with information such as the URL that is being crawled and HTTP method
+ // - body: the HTML code of the current page
+ async requestHandler({ request, body }) {
+ log.debug(`Processing ${request.url}...`);
+
+ // Store the results to the dataset. In local configuration,
+ // the data will be stored as JSON files in ./storage/datasets/default
+ await Dataset.pushData({
+ url: request.url,
+ body,
+ });
+ },
+
+ // This function is called if the page processing failed more than maxRequestRetries + 1 times.
+ failedRequestHandler({ request }) {
+ log.debug(`Request ${request.url} failed twice.`);
+ },
+});
+
+// Run the crawler and wait for it to finish.
+await crawler.run([
+ 'https://crawlee.dev',
+]);
+
+log.debug('Crawler finished.');
diff --git a/docs/examples/tsconfig.json b/docs/examples/tsconfig.json
index 21a046453..397bead8b 100644
--- a/docs/examples/tsconfig.json
+++ b/docs/examples/tsconfig.json
@@ -6,6 +6,7 @@
"crawlee": ["packages/crawlee/src"],
"@crawlee/basic": ["packages/basic-crawler/src"],
"@crawlee/browser": ["packages/browser-crawler/src"],
+ "@crawlee/http": ["packages/http-crawler/src"],
"@crawlee/cheerio": ["packages/cheerio-crawler/src"],
"@crawlee/playwright": ["packages/playwright-crawler/src"],
"@crawlee/puppeteer": ["packages/puppeteer-crawler/src"],
diff --git a/docs/guides/proxy_management.mdx b/docs/guides/proxy_management.mdx
index 896cc3ded..a2a2e779a 100644
--- a/docs/guides/proxy_management.mdx
+++ b/docs/guides/proxy_management.mdx
@@ -10,13 +10,16 @@ import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import CodeBlock from '@theme/CodeBlock';
+import HttpSource from '!!raw-loader!./proxy_management_integration_http.ts';
import CheerioSource from '!!raw-loader!./proxy_management_integration_cheerio.ts';
import PlaywrightSource from '!!raw-loader!./proxy_management_integration_playwright.ts';
import PuppeteerSource from '!!raw-loader!./proxy_management_integration_puppeteer.ts';
import SessionStandaloneSource from '!!raw-loader!./proxy_management_session_standalone.ts';
+import SessionHttpSource from '!!raw-loader!./proxy_management_session_http.ts';
import SessionCheerioSource from '!!raw-loader!./proxy_management_session_cheerio.ts';
import SessionPlaywrightSource from '!!raw-loader!./proxy_management_session_playwright.ts';
import SessionPuppeteerSource from '!!raw-loader!./proxy_management_session_puppeteer.ts';
+import InspectionHttpSource from '!!raw-loader!./proxy_management_inspection_http.ts';
import InspectionCheerioSource from '!!raw-loader!./proxy_management_inspection_cheerio.ts';
import InspectionPlaywrightSource from '!!raw-loader!./proxy_management_inspection_playwright.ts';
import InspectionPuppeteerSource from '!!raw-loader!./proxy_management_inspection_puppeteer.ts';
@@ -55,9 +58,14 @@ All our proxy needs are managed by the <ApiLink to="core/class/ProxyConfiguratio
### Crawler integration
-`ProxyConfiguration` integrates seamlessly into <ApiLink to="cheerio-crawler/class/CheerioCrawler">`CheerioCrawler`</ApiLink>, <ApiLink to="playwright-crawler/class/PlaywrightCrawler">`PlaywrightCrawler`</ApiLink> and <ApiLink to="puppeteer-crawler/class/PuppeteerCrawler">`PuppeteerCrawler`</ApiLink>.
+`ProxyConfiguration` integrates seamlessly into <ApiLink to="http-crawler/class/HttpCrawler">`HttpCrawler`</ApiLink>, <ApiLink to="cheerio-crawler/class/CheerioCrawler">`CheerioCrawler`</ApiLink>, <ApiLink to="playwright-crawler/class/PlaywrightCrawler">`PlaywrightCrawler`</ApiLink> and <ApiLink to="puppeteer-crawler/class/PuppeteerCrawler">`PuppeteerCrawler`</ApiLink>.
<Tabs groupId="proxy_session_management">
+ <TabItem value="http" label="HttpCrawler">
+ <CodeBlock language="js">
+ {HttpSource}
+ </CodeBlock>
+ </TabItem>
<TabItem value="cheerio" label="CheerioCrawler" default>
<CodeBlock language="js">
{CheerioSource}
@@ -84,6 +92,11 @@ Our crawlers will now use the selected proxies for all connections.
When no `sessionId` is provided, our proxy URLs are rotated round-robin.
<Tabs groupId="proxy_session_management">
+ <TabItem value="http" label="HttpCrawler">
+ <CodeBlock language="js">
+ {SessionHttpSource}
+ </CodeBlock>
+ </TabItem>
<TabItem value="cheerio" label="CheerioCrawler" default>
<CodeBlock language="js">
{SessionCheerioSource}
@@ -108,11 +121,16 @@ When no `sessionId` is provided, our proxy URLs are rotated round-robin.
## Inspecting current proxy in Crawlers
-`CheerioCrawler`, `PlaywrightCrawler` and `PuppeteerCrawler` grant access to information about the currently used proxy
+`HttpCrawler`, `CheerioCrawler`, `PlaywrightCrawler` and `PuppeteerCrawler` grant access to information about the currently used proxy
in their `requestHandler` using a <ApiLink to="core/interface/ProxyInfo">`proxyInfo`</ApiLink> object.
With the `proxyInfo` object, we can easily access the proxy URL.
<Tabs groupId="proxy_session_management">
+ <TabItem value="http" label="HttpCrawler">
+ <CodeBlock language="js">
+ {InspectionHttpSource}
+ </CodeBlock>
+ </TabItem>
<TabItem value="cheerio" label="CheerioCrawler" default>
<CodeBlock language="js">
{InspectionCheerioSource}
diff --git a/docs/guides/proxy_management_inspection_http.ts b/docs/guides/proxy_management_inspection_http.ts
new file mode 100644
index 000000000..076350877
--- /dev/null
+++ b/docs/guides/proxy_management_inspection_http.ts
@@ -0,0 +1,11 @@
+import { HttpCrawler, ProxyConfiguration } from 'crawlee';
+
+const proxyConfiguration = new ProxyConfiguration({ /* opts */ });
+
+const crawler = new HttpCrawler({
+ proxyConfiguration,
+ async requestHandler({ proxyInfo }) {
+ console.log(proxyInfo);
+ },
+ // ...
+});
diff --git a/docs/guides/proxy_management_integration_http.ts b/docs/guides/proxy_management_integration_http.ts
new file mode 100644
index 000000000..0db0a9ab9
--- /dev/null
+++ b/docs/guides/proxy_management_integration_http.ts
@@ -0,0 +1,13 @@
+import { HttpCrawler, ProxyConfiguration } from 'crawlee';
+
+const proxyConfiguration = new ProxyConfiguration({
+ proxyUrls: [
+ 'http://proxy-1.com',
+ 'http://proxy-2.com',
+ ],
+});
+
+const crawler = new HttpCrawler({
+ proxyConfiguration,
+ // ...
+});
diff --git a/docs/guides/proxy_management_session_http.ts b/docs/guides/proxy_management_session_http.ts
new file mode 100644
index 000000000..601e26812
--- /dev/null
+++ b/docs/guides/proxy_management_session_http.ts
@@ -0,0 +1,10 @@
+import { HttpCrawler, ProxyConfiguration } from 'crawlee';
+
+const proxyConfiguration = new ProxyConfiguration({ /* opts */ });
+
+const crawler = new HttpCrawler({
+ useSessionPool: true,
+ persistCookiesPerSession: true,
+ proxyConfiguration,
+ // ...
+});
diff --git a/docs/guides/session_management.mdx b/docs/guides/session_management.mdx
index 03458559c..a7dc34e16 100644
--- a/docs/guides/session_management.mdx
+++ b/docs/guides/session_management.mdx
@@ -11,6 +11,7 @@ import TabItem from '@theme/TabItem';
import CodeBlock from '@theme/CodeBlock';
import BasicSource from '!!raw-loader!./session_management_basic.ts';
+import HttpSource from '!!raw-loader!./session_management_http.ts';
import CheerioSource from '!!raw-loader!./session_management_cheerio.ts';
import PlaywrightSource from '!!raw-loader!./session_management_playwright.ts';
import PuppeteerSource from '!!raw-loader!./session_management_puppeteer.ts';
@@ -27,17 +28,23 @@ which should prevent burning out a small pool of available IPs.
Now let's take a look at the examples of how to use Session pool:
- with <ApiLink to="basic-crawler/class/BasicCrawler">`BasicCrawler`</ApiLink>;
+- with <ApiLink to="http-crawler/class/HttpCrawler">`HttpCrawler`</ApiLink>;
- with <ApiLink to="cheerio-crawler/class/CheerioCrawler">`CheerioCrawler`</ApiLink>;
- with <ApiLink to="playwright-crawler/class/PlaywrightCrawler">`PlaywrightCrawler`</ApiLink>;
- with <ApiLink to="puppeteer-crawler/class/PuppeteerCrawler">`PuppeteerCrawler`</ApiLink>;
- without a crawler (standalone usage to manage sessions manually).
<Tabs groupId="session_pool">
- <TabItem value="basic" label="BasicCrawler" default>
+ <TabItem value="basic" label="BasicCrawler">
<CodeBlock language="js">
{BasicSource}
</CodeBlock>
</TabItem>
+ <TabItem value="http" label="HttpCrawler">
+ <CodeBlock language="js">
+ {HttpSource}
+ </CodeBlock>
+ </TabItem>
<TabItem value="cheerio" label="CheerioCrawler" default>
<CodeBlock language="js">
{CheerioSource}
diff --git a/docs/guides/session_management_http.ts b/docs/guides/session_management_http.ts
new file mode 100644
index 000000000..cfb83cd70
--- /dev/null
+++ b/docs/guides/session_management_http.ts
@@ -0,0 +1,26 @@
+import { HttpCrawler, ProxyConfiguration } from 'crawlee';
+
+const proxyConfiguration = new ProxyConfiguration({ /* opts */ });
+
+const crawler = new HttpCrawler({
+ // To use the proxy IP session rotation logic, you must turn the proxy usage on.
+ proxyConfiguration,
+ // Activates the Session pool (default is true).
+ useSessionPool: true,
+ // Overrides default Session pool configuration.
+ sessionPoolOptions: { maxPoolSize: 100 },
+ // Set to true if you want the crawler to save cookies per session,
+ // and set the cookie header to request automatically (default is true).
+ persistCookiesPerSession: true,
+ async requestHandler({ session, body }) {
+ const title = body.match(/<title>(.*?)<\/title>/)?.[1];
+
+ if (title === 'Blocked') {
+ session.retire();
+ } else if (title === 'Not sure if blocked, might also be a connection error') {
+ session.markBad();
+ } else {
+ // session.markGood() - this step is done automatically in BasicCrawler.
+ }
+ },
+});
diff --git a/docs/upgrading/upgrading_v3.md b/docs/upgrading/upgrading_v3.md
index 6dccbf87e..79ae4b284 100644
--- a/docs/upgrading/upgrading_v3.md
+++ b/docs/upgrading/upgrading_v3.md
@@ -22,6 +22,7 @@ The [`crawlee`](https://www.npmjs.com/package/crawlee) package consists of sever
- `@crawlee/core`: the base for all the crawler implementations, also contains things like `Request`, `RequestQueue`, `RequestList` or `Dataset` classes
- `@crawlee/basic`: exports `BasicCrawler`
+- `@crawlee/http`: exports `HttpCrawler` (which is used for creating `@crawlee/cheerio`)
- `@crawlee/cheerio`: exports `CheerioCrawler`
- `@crawlee/browser`: exports `BrowserCrawler` (which is used for creating `@crawlee/playwright` and `@crawlee/puppeteer`)
- `@crawlee/playwright`: exports `PlaywrightCrawler`
diff --git a/jest.config.js b/jest.config.js
index 471a86f44..22b2f89f2 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -15,6 +15,7 @@ module.exports = {
'^crawlee$': '<rootDir>/packages/crawlee/src',
'^@crawlee/basic$': '<rootDir>/packages/basic-crawler/src',
'^@crawlee/browser$': '<rootDir>/packages/browser-crawler/src',
+ '^@crawlee/http$': '<rootDir>/packages/http-crawler/src',
'^@crawlee/cheerio$': '<rootDir>/packages/cheerio-crawler/src',
'^@crawlee/playwright$': '<rootDir>/packages/playwright-crawler/src',
'^@crawlee/puppeteer$': '<rootDir>/packages/puppeteer-crawler/src',
diff --git a/package-lock.json b/package-lock.json
index 828d22041..2fb14e7dc 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1030,6 +1030,10 @@
"resolved": "packages/core",
"link": true
},
+ "node_modules/@crawlee/http": {
+ "resolved": "packages/http-crawler",
+ "link": true
+ },
"node_modules/@crawlee/memory-storage": {
"resolved": "packages/memory-storage",
"link": true
@@ -15969,31 +15973,15 @@
"version": "3.0.3",
"license": "Apache-2.0",
"dependencies": {
- "@apify/timeout": "^0.3.0",
- "@apify/utilities": "^2.0.0",
- "@crawlee/basic": "^3.0.3",
- "@types/content-type": "^1.1.5",
+ "@crawlee/http": "^3.0.3",
+ "@crawlee/types": "^3.0.3",
"cheerio": "1.0.0-rc.12",
- "content-type": "^1.0.4",
- "htmlparser2": "^8.0.1",
- "iconv-lite": "^0.6.3",
- "ow": "^0.28.1"
+ "htmlparser2": "^8.0.1"
},
"engines": {
"node": ">=16.0.0"
}
},
- "packages/cheerio-crawler/node_modules/iconv-lite": {
- "version": "0.6.3",
- "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
- "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
- "dependencies": {
- "safer-buffer": ">= 2.1.2 < 3.0.0"
- },
- "engines": {
- "node": ">=0.10.0"
- }
- },
"packages/cli": {
"name": "@crawlee/cli",
"version": "3.0.3",
@@ -16093,6 +16081,37 @@
}
}
},
+ "packages/http-crawler": {
+ "name": "@crawlee/http",
+ "version": "3.0.3",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@apify/timeout": "^0.3.0",
+ "@apify/utilities": "^2.0.0",
+ "@crawlee/basic": "^3.0.3",
+ "@crawlee/types": "^3.0.3",
+ "@types/content-type": "^1.1.5",
+ "content-type": "^1.0.4",
+ "got-scraping": "^3.2.9",
+ "iconv-lite": "^0.6.3",
+ "mime-types": "^2.1.35",
+ "ow": "^0.28.1"
+ },
+ "engines": {
+ "node": ">=16.0.0"
+ }
+ },
+ "packages/http-crawler/node_modules/iconv-lite": {
+ "version": "0.6.3",
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
+ "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
+ "dependencies": {
+ "safer-buffer": ">= 2.1.2 < 3.0.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"packages/memory-storage": {
"name": "@crawlee/memory-storage",
"version": "3.0.3",
@@ -16486,8 +16505,6 @@
"cheerio": "1.0.0-rc.12",
"content-type": "^1.0.4",
"got-scraping": "^3.2.9",
- "mime-types": "^2.1.35",
- "ow": "^0.28.1",
"tslib": "^2.4.0"
},
"engines": {
@@ -17279,25 +17296,10 @@
"@crawlee/cheerio": {
"version": "file:packages/cheerio-crawler",
"requires": {
- "@apify/timeout": "^0.3.0",
- "@apify/utilities": "^2.0.0",
- "@crawlee/basic": "^3.0.3",
- "@types/content-type": "^1.1.5",
+ "@crawlee/http": "^3.0.3",
+ "@crawlee/types": "^3.0.3",
"cheerio": "1.0.0-rc.12",
- "content-type": "^1.0.4",
- "htmlparser2": "^8.0.1",
- "iconv-lite": "^0.6.3",
- "ow": "^0.28.1"
- },
- "dependencies": {
- "iconv-lite": {
- "version": "0.6.3",
- "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
- "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
- "requires": {
- "safer-buffer": ">= 2.1.2 < 3.0.0"
- }
- }
+ "htmlparser2": "^8.0.1"
}
},
"@crawlee/cli": {
@@ -17352,6 +17354,31 @@
}
}
},
+ "@crawlee/http": {
+ "version": "file:packages/http-crawler",
+ "requires": {
+ "@apify/timeout": "^0.3.0",
+ "@apify/utilities": "^2.0.0",
+ "@crawlee/basic": "^3.0.3",
+ "@crawlee/types": "^3.0.3",
+ "@types/content-type": "^1.1.5",
+ "content-type": "^1.0.4",
+ "got-scraping": "^3.2.9",
+ "iconv-lite": "^0.6.3",
+ "mime-types": "*",
+ "ow": "^0.28.1"
+ },
+ "dependencies": {
+ "iconv-lite": {
+ "version": "0.6.3",
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
+ "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
+ "requires": {
+ "safer-buffer": ">= 2.1.2 < 3.0.0"
+ }
+ }
+ }
+ },
"@crawlee/memory-storage": {
"version": "file:packages/memory-storage",
"requires": {
@@ -17588,8 +17615,6 @@
"cheerio": "1.0.0-rc.12",
"content-type": "^1.0.4",
"got-scraping": "^3.2.9",
- "mime-types": "^2.1.35",
- "ow": "^0.28.1",
"tslib": "^2.4.0"
}
},
diff --git a/packages/cheerio-crawler/README.md b/packages/cheerio-crawler/README.md
index 687ed90f5..c16a4c601 100644
--- a/packages/cheerio-crawler/README.md
+++ b/packages/cheerio-crawler/README.md
@@ -22,7 +22,7 @@ preNavigationHooks: [
]
```
-By default, `CheerioCrawler` only processes web pages with the `text/html` and `application/xhtml+xml` MIME content types (as reported by the `Content-Type` HTTP header), and skips pages with other content types. If you want the crawler to process other content types, use the [CheerioCrawlerOptions.additionalMimeTypes](https://crawlee.dev/api/cheerio-crawler/interface/CheerioCrawlerOptions#additionalMimeTypes) constructor option. Beware that the parsing behavior differs for HTML, XML, JSON and other types of content. For details, see [CheerioCrawlerOptions.requestHandler](https://crawlee.dev/api/cheerio-crawler/interface/CheerioCrawlerOptions#requestHandler).
+By default, `CheerioCrawler` only processes web pages with the `text/html` and `application/xhtml+xml` MIME content types (as reported by the `Content-Type` HTTP header), and skips pages with other content types. If you want the crawler to process other content types, use the [CheerioCrawlerOptions.additionalMimeTypes](https://crawlee.dev/api/cheerio-crawler/interface/CheerioCrawlerOptions#additionalMimeTypes) constructor option. Beware that the parsing behavior differs for HTML, XML, JSON and other types of content. For more details, see [CheerioCrawlerOptions.requestHandler](https://crawlee.dev/api/cheerio-crawler/interface/CheerioCrawlerOptions#requestHandler).
New requests are only dispatched when there is enough free CPU and memory available, using the functionality provided by the [AutoscaledPool](https://crawlee.dev/api/core/class/AutoscaledPool) class. All [AutoscaledPool](https://crawlee.dev/api/core/class/AutoscaledPool) configuration options can be passed to the `autoscaledPoolOptions` parameter of the `CheerioCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency` [AutoscaledPool](https://crawlee.dev/api/core/class/AutoscaledPool) options are available directly in the `CheerioCrawler` constructor.
diff --git a/packages/cheerio-crawler/package.json b/packages/cheerio-crawler/package.json
index 7147ab0e2..a12cc5b3b 100644
--- a/packages/cheerio-crawler/package.json
+++ b/packages/cheerio-crawler/package.json
@@ -53,14 +53,9 @@
"access": "public"
},
"dependencies": {
- "@apify/timeout": "^0.3.0",
- "@apify/utilities": "^2.0.0",
- "@crawlee/basic": "^3.0.3",
- "@types/content-type": "^1.1.5",
+ "@crawlee/http": "^3.0.3",
+ "@crawlee/types": "^3.0.3",
"cheerio": "1.0.0-rc.12",
- "content-type": "^1.0.4",
- "htmlparser2": "^8.0.1",
- "iconv-lite": "^0.6.3",
- "ow": "^0.28.1"
+ "htmlparser2": "^8.0.1"
}
}
diff --git a/packages/cheerio-crawler/src/index.ts b/packages/cheerio-crawler/src/index.ts
index 1d698afe4..f4c05bc08 100644
--- a/packages/cheerio-crawler/src/index.ts
+++ b/packages/cheerio-crawler/src/index.ts
@@ -1,2 +1,2 @@
-export * from '@crawlee/basic';
+export * from '@crawlee/http';
export * from './internals/cheerio-crawler';
diff --git a/packages/cheerio-crawler/src/internals/cheerio-crawler.ts b/packages/cheerio-crawler/src/internals/cheerio-crawler.ts
index 1a8feae6e..08ae20404 100644
--- a/packages/cheerio-crawler/src/internals/cheerio-crawler.ts
+++ b/packages/cheerio-crawler/src/internals/cheerio-crawler.ts
@@ -1,40 +1,20 @@
-import { addTimeoutToPromise, tryCancel } from '@apify/timeout';
-import { concatStreamToBuffer, readStreamToString } from '@apify/utilities';
-import type { AutoscaledPoolOptions, BasicCrawlerOptions, ErrorHandler, RequestHandler } from '@crawlee/basic';
-import { BasicCrawler, BASIC_CRAWLER_TIMEOUT_BUFFER_SECS } from '@crawlee/basic';
-import type { CrawlingContext, EnqueueLinksOptions, ProxyConfiguration, Request, RequestQueue, Session } from '@crawlee/core';
-import { CrawlerExtension, enqueueLinks, mergeCookies, Router, resolveBaseUrlForEnqueueLinksFiltering, validators, Configuration } from '@crawlee/core';
-import type { BatchAddRequestsResult, Awaitable, Dictionary } from '@crawlee/types';
-import type { CheerioRoot } from '@crawlee/utils';
-import { entries, parseContentTypeFromResponse } from '@crawlee/utils';
+import type {
+ HttpCrawlerOptions,
+ InternalHttpCrawlingContext,
+ InternalHttpHook,
+ ErrorHandler,
+ RequestHandler,
+ EnqueueLinksOptions,
+ RequestQueue,
+ Configuration,
+} from '@crawlee/http';
+import { HttpCrawler, enqueueLinks, Router, resolveBaseUrlForEnqueueLinksFiltering } from '@crawlee/http';
+import type { BatchAddRequestsResult, Dictionary } from '@crawlee/types';
import type { CheerioOptions } from 'cheerio';
import * as cheerio from 'cheerio';
-import type { RequestLike, ResponseLike } from 'content-type';
-import contentTypeParser from 'content-type';
-import type { OptionsInit, Method, Request as GotRequest, Response as GotResponse, GotOptionsInit } from 'got-scraping';
-import { gotScraping, TimeoutError } from 'got-scraping';
import { DomHandler } from 'htmlparser2';
import { WritableStream } from 'htmlparser2/lib/WritableStream';
-import type { IncomingHttpHeaders, IncomingMessage } from 'http';
-import iconv from 'iconv-lite';
-import ow from 'ow';
-import util from 'util';
-
-/**
- * Default mime types, which CheerioScraper supports.
- */
-const HTML_AND_XML_MIME_TYPES = ['text/html', 'text/xml', 'application/xhtml+xml', 'application/xml'];
-const APPLICATION_JSON_MIME_TYPE = 'application/json';
-const CHEERIO_OPTIMIZED_AUTOSCALED_POOL_OPTIONS: AutoscaledPoolOptions = {
- desiredConcurrency: 10,
- snapshotterOptions: {
- eventLoopSnapshotIntervalSecs: 2,
- maxBlockedMillis: 100,
- },
- systemStatusOptions: {
- maxEventLoopOverloadedRatio: 0.7,
- },
-};
+import type { IncomingMessage } from 'http';
export type CheerioErrorHandler<
UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
@@ -44,240 +24,24 @@ export type CheerioErrorHandler<
export interface CheerioCrawlerOptions<
UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
JSONData extends Dictionary = Dictionary,
- > extends Omit<BasicCrawlerOptions<CheerioCrawlingContext<UserData, JSONData>>,
- // Overridden with cheerio context
- | 'requestHandler'
- | 'handleRequestFunction'
-
- | 'failedRequestHandler'
- | 'handleFailedRequestFunction'
- | 'handleRequestTimeoutSecs'
-
- | 'errorHandler'
- > {
- /**
- * User-provided function that performs the logic of the crawler. It is called for each page
- * loaded and parsed by the crawler.
- *
- * The function receives the {@apilink CheerioCrawlingContext} as an argument,
- * where the {@apilink CheerioCrawlingContext.request} instance represents the URL to crawl.
- *
- * Type of {@apilink CheerioCrawlingContext.body} depends on the `Content-Type` header of the web page:
- * - String for `text/html`, `application/xhtml+xml`, `application/xml` MIME content types
- * - Buffer for others MIME content types
- *
- * Parsed `Content-Type` header using
- * [content-type package](https://www.npmjs.com/package/content-type)
- * is stored in {@apilink CheerioCrawlingContext.contentType}`.
- *
- * Cheerio is available only for HTML and XML content types.
- *
- * If the function returns, the returned promise is awaited by the crawler.
- *
- * If the function throws an exception, the crawler will try to re-crawl the
- * request later, up to `option.maxRequestRetries` times.
- * If all the retries fail, the crawler calls the function
- * provided to the `failedRequestHandler` parameter.
- * To make this work, you should **always**
- * let your function throw exceptions rather than catch them.
- * The exceptions are logged to the request using the
- * {@apilink Request.pushErrorMessage} function.
- */
- requestHandler?: CheerioRequestHandler<UserData, JSONData>;
-
- /**
- * User-provided function that performs the logic of the crawler. It is called for each page
- * loaded and parsed by the crawler.
- *
- * The function receives the {@apilink CheerioCrawlingContext} as an argument,
- * where the {@apilink CheerioCrawlingContext.request} instance represents the URL to crawl.
- *
- * Type of {@apilink CheerioCrawlingContext.body} depends on the `Content-Type` header of the web page:
- * - String for `text/html`, `application/xhtml+xml`, `application/xml` MIME content types
- * - Buffer for others MIME content types
- *
- * Parsed `Content-Type` header using
- * [content-type package](https://www.npmjs.com/package/content-type)
- * is stored in {@apilink CheerioCrawlingContext.contentType}`.
- *
- * Cheerio is available only for HTML and XML content types.
- *
- * If the function returns, the returned promise is awaited by the crawler.
- *
- * If the function throws an exception, the crawler will try to re-crawl the
- * request later, up to `option.maxRequestRetries` times.
- * If all the retries fail, the crawler calls the function
- * provided to the `failedRequestHandler` parameter.
- * To make this work, you should **always**
- * let your function throw exceptions rather than catch them.
- * The exceptions are logged to the request using the
- * {@apilink Request.pushErrorMessage} function.
- *
- * @deprecated `handlePageFunction` has been renamed to `requestHandler` and will be removed in a future version.
- * @ignore
- */
- handlePageFunction?: CheerioRequestHandler<UserData, JSONData>;
-
- /**
- * Timeout in which the HTTP request to the resource needs to finish, given in seconds.
- */
- navigationTimeoutSecs?: number;
-
- /**
- * If set to true, SSL certificate errors will be ignored.
- */
- ignoreSslErrors?: boolean;
-
- /**
- * If set, `CheerioCrawler` will be configured for all connections to use
- * [Apify Proxy](https://console.apify.com/proxy) or your own Proxy URLs provided and rotated according to the configuration.
- * For more information, see the [documentation](https://docs.apify.com/proxy).
- */
- proxyConfiguration?: ProxyConfiguration;
-
- /**
- * User-provided function that allows modifying the request object before it gets retried by the crawler.
- * It's executed before each retry for the requests that failed less than `option.maxRequestRetries` times.
- *
- * The function receives the {@apilink CheerioCrawlingContext} as the first argument,
- * where the {@apilink CheerioCrawlingContext.request} corresponds to the request to be retried.
- * Second argument is the `Error` instance that
- * represents the last error thrown during processing of the request.
- */
- errorHandler?: CheerioErrorHandler<UserData, JSONData>;
-
- /**
- * A function to handle requests that failed more than `option.maxRequestRetries` times.
- *
- * The function receives the {@apilink CheerioCrawlingContext} as the first argument,
- * where the {@apilink CheerioCrawlingContext.request} corresponds to the failed request.
- * Second argument is the `Error` instance that
- * represents the last error thrown during processing of the request.
- *
- * See [source code](https://github.com/apify/crawlee/blob/master/src/crawlers/cheerio_crawler.js#L13)
- * for the default implementation of this function.
- */
- failedRequestHandler?: CheerioErrorHandler<UserData, JSONData>;
-
- /**
- * A function to handle requests that failed more than `option.maxRequestRetries` times.
- *
- * The function receives the {@apilink CheerioCrawlingContext} as the first argument,
- * where the {@apilink CheerioCrawlingContext.request} corresponds to the failed request.
- * Second argument is the `Error` instance that
- * represents the last error thrown during processing of the request.
- *
- * See [source code](https://github.com/apify/crawlee/blob/master/src/crawlers/cheerio_crawler.js#L13)
- * for the default implementation of this function.
- *
- * @deprecated `handleFailedRequestFunction` has been renamed to `failedRequestHandler` and will be removed in a future version.
- * @ignore
- */
- handleFailedRequestFunction?: CheerioErrorHandler<UserData, JSONData>;
-
- /**
- * Async functions that are sequentially evaluated before the navigation. Good for setting additional cookies
- * or browser properties before navigation. The function accepts two parameters, `crawlingContext` and `gotOptions`,
- * which are passed to the `requestAsBrowser()` function the crawler calls to navigate.
- * Example:
- * ```
- * preNavigationHooks: [
- * async (crawlingContext, gotOptions) => {
- * // ...
- * },
- * ]
- * ```
- */
- preNavigationHooks?: CheerioHook<UserData, JSONData>[];
-
- /**
- * Async functions that are sequentially evaluated after the navigation. Good for checking if the navigation was successful.
- * The function accepts `crawlingContext` as the only parameter.
- * Example:
- * ```
- * postNavigationHooks: [
- * async (crawlingContext) => {
- * // ...
- * },
- * ]
- * ```
- */
- postNavigationHooks?: CheerioHook<UserData, JSONData>[];
-
- /**
- * An array of [MIME types](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types)
- * you want the crawler to load and process. By default, only `text/html` and `application/xhtml+xml` MIME types are supported.
- */
- additionalMimeTypes?: string[];
-
- /**
- * By default `CheerioCrawler` will extract correct encoding from the HTTP response headers.
- * Sadly, there are some websites which use invalid headers. Those are encoded using the UTF-8 encoding.
- * If those sites actually use a different encoding, the response will be corrupted. You can use
- * `suggestResponseEncoding` to fall back to a certain encoding, if you know that your target website uses it.
- * To force a certain encoding, disregarding the response headers, use {@apilink CheerioCrawlerOptions.forceResponseEncoding}
- * ```
- * // Will fall back to windows-1250 encoding if none found
- * suggestResponseEncoding: 'windows-1250'
- * ```
- */
- suggestResponseEncoding?: string;
-
- /**
- * By default `CheerioCrawler` will extract correct encoding from the HTTP response headers. Use `forceResponseEncoding`
- * to force a certain encoding, disregarding the response headers.
- * To only provide a default for missing encodings, use {@apilink CheerioCrawlerOptions.suggestResponseEncoding}
- * ```
- * // Will force windows-1250 encoding even if headers say otherwise
- * forceResponseEncoding: 'windows-1250'
- * ```
- */
- forceResponseEncoding?: string;
-
- /**
- * Automatically saves cookies to Session. Works only if Session Pool is used.
- *
- * It parses cookie from response "set-cookie" header saves or updates cookies for session and once the session is used for next request.
- * It passes the "Cookie" header to the request with the session cookies.
- */
- persistCookiesPerSession?: boolean;
-}
+ > extends HttpCrawlerOptions<CheerioCrawlingContext<UserData, JSONData>> {}
export type CheerioHook<
UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
JSONData extends Dictionary = Dictionary,
- > = (
- crawlingContext: CheerioCrawlingContext<UserData, JSONData>,
- gotOptions: OptionsInit,
-) => Awaitable<void>;
+ > = InternalHttpHook<CheerioCrawlingContext<UserData, JSONData>>;
export interface CheerioCrawlingContext<
UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
JSONData extends Dictionary = Dictionary,
- > extends CrawlingContext<UserData> {
+ > extends InternalHttpCrawlingContext<UserData, JSONData, CheerioCrawler> {
/**
* The [Cheerio](https://cheerio.js.org/) object with parsed HTML.
+ * Cheerio is available only for HTML and XML content types.
*/
- $: CheerioRoot;
-
- /**
- * The request body of the web page.
- */
- body: (string | Buffer);
-
- /**
- * The parsed object from JSON string if the response contains the content type application/json.
- */
- json: JSONData;
+ $: cheerio.CheerioAPI;
- /**
- * Parsed `Content-Type header: { type, encoding }`.
- */
- contentType: { type: string; encoding: string };
- crawler: CheerioCrawler;
- response: IncomingMessage;
enqueueLinks: (options?: CheerioCrawlerEnqueueLinksOptions) => Promise<BatchAddRequestsResult>;
- sendRequest: (overrideOptions?: Partial<GotOptionsInit>) => Promise<GotResponse<string>>;
}
export type CheerioRequestHandler<
@@ -327,7 +91,7 @@ export interface CheerioCrawlerEnqueueLinksOptions extends Omit<EnqueueLinksOpti
* and skips pages with other content types. If you want the crawler to process other content types,
* use the {@apilink CheerioCrawlerOptions.additionalMimeTypes} constructor option.
* Beware that the parsing behavior differs for HTML, XML, JSON and other types of content.
- * For details, see {@apilink CheerioCrawlerOptions.requestHandler}.
+ * For more details, see {@apilink CheerioCrawlerOptions.requestHandler}.
*
* New requests are only dispatched when there is enough free CPU and memory available,
* using the functionality provided by the {@apilink AutoscaledPool} class.
@@ -363,195 +127,33 @@ export interface CheerioCrawlerEnqueueLinksOptions extends Omit<EnqueueLinksOpti
* ```
* @category Crawlers
*/
-export class CheerioCrawler extends BasicCrawler<CheerioCrawlingContext> {
- /**
- * A reference to the underlying {@apilink ProxyConfiguration} class that manages the crawler's proxies.
- * Only available if used by the crawler.
- */
- proxyConfiguration?: ProxyConfiguration;
-
- protected userRequestHandlerTimeoutMillis: number;
- protected preNavigationHooks: CheerioHook[];
- protected postNavigationHooks: CheerioHook[];
- protected persistCookiesPerSession: boolean;
- protected navigationTimeoutMillis: number;
- protected ignoreSslErrors: boolean;
- protected suggestResponseEncoding?: string;
- protected forceResponseEncoding?: string;
- protected readonly supportedMimeTypes: Set<string>;
-
- protected static override optionsShape = {
- ...BasicCrawler.optionsShape,
- handlePageFunction: ow.optional.function,
-
- navigationTimeoutSecs: ow.optional.number,
- ignoreSslErrors: ow.optional.boolean,
- additionalMimeTypes: ow.optional.array.ofType(ow.string),
- suggestResponseEncoding: ow.optional.string,
- forceResponseEncoding: ow.optional.string,
- proxyConfiguration: ow.optional.object.validate(validators.proxyConfiguration),
- persistCookiesPerSession: ow.optional.boolean,
-
- preNavigationHooks: ow.optional.array,
- postNavigationHooks: ow.optional.array,
- };
-
+export class CheerioCrawler extends HttpCrawler<CheerioCrawlingContext> {
/**
* All `CheerioCrawler` parameters are passed via an options object.
*/
- constructor(options: CheerioCrawlerOptions = {}, override readonly config = Configuration.getGlobalConfig()) {
- ow(options, 'CheerioCrawlerOptions', ow.object.exactShape(CheerioCrawler.optionsShape));
-
- const {
- requestHandler,
- handlePageFunction,
-
- requestHandlerTimeoutSecs = 60,
- navigationTimeoutSecs = 30,
- ignoreSslErrors = true,
- additionalMimeTypes = [],
- suggestResponseEncoding,
- forceResponseEncoding,
- proxyConfiguration,
- persistCookiesPerSession,
- preNavigationHooks = [],
- postNavigationHooks = [],
-
- // Ignored
- handleRequestFunction,
-
- // BasicCrawler
- autoscaledPoolOptions = CHEERIO_OPTIMIZED_AUTOSCALED_POOL_OPTIONS,
- ...basicCrawlerOptions
- } = options;
-
- super({
- ...basicCrawlerOptions,
- requestHandler,
- autoscaledPoolOptions,
- // We need to add some time for internal functions to finish,
- // but not too much so that we would stall the crawler.
- requestHandlerTimeoutSecs: navigationTimeoutSecs + requestHandlerTimeoutSecs + BASIC_CRAWLER_TIMEOUT_BUFFER_SECS,
- }, config);
-
- this._handlePropertyNameChange({
- newName: 'requestHandler',
- oldName: 'handlePageFunction',
- propertyKey: 'requestHandler',
- newProperty: requestHandler,
- oldProperty: handlePageFunction,
- allowUndefined: true,
- });
-
- if (!this.requestHandler) {
- this.requestHandler = this.router;
- }
-
- // Cookies should be persisted per session only if session pool is used
- if (!this.useSessionPool && persistCookiesPerSession) {
- throw new Error('You cannot use "persistCookiesPerSession" without "useSessionPool" set to true.');
- }
-
- this.supportedMimeTypes = new Set([...HTML_AND_XML_MIME_TYPES, APPLICATION_JSON_MIME_TYPE]);
- if (additionalMimeTypes.length) this._extendSupportedMimeTypes(additionalMimeTypes);
-
- if (suggestResponseEncoding && forceResponseEncoding) {
- this.log.warning('Both forceResponseEncoding and suggestResponseEncoding options are set. Using forceResponseEncoding.');
- }
-
- this.userRequestHandlerTimeoutMillis = requestHandlerTimeoutSecs * 1000;
- this.navigationTimeoutMillis = navigationTimeoutSecs * 1000;
- this.ignoreSslErrors = ignoreSslErrors;
- this.suggestResponseEncoding = suggestResponseEncoding;
- this.forceResponseEncoding = forceResponseEncoding;
- this.proxyConfiguration = proxyConfiguration;
- this.preNavigationHooks = preNavigationHooks;
- this.postNavigationHooks = [
- ({ request, response }) => this._abortDownloadOfBody(request, response!),
- ...postNavigationHooks,
- ];
-
- if (this.useSessionPool) {
- this.persistCookiesPerSession = persistCookiesPerSession ?? true;
- } else {
- this.persistCookiesPerSession = false;
- }
- }
-
- /**
- * **EXPERIMENTAL**
- * Function for attaching CrawlerExtensions such as the Unblockers.
- * @param extension Crawler extension that overrides the crawler configuration.
- */
- use(extension: CrawlerExtension) {
- ow(extension, ow.object.instanceOf(CrawlerExtension));
-
- const extensionOptions = extension.getCrawlerOptions();
-
- for (const [key, value] of entries(extensionOptions)) {
- const isConfigurable = this.hasOwnProperty(key);
- const originalType = typeof this[key as keyof this];
- const extensionType = typeof value; // What if we want to null something? It is really needed?
- const isSameType = originalType === extensionType || value == null; // fast track for deleting keys
- const exists = this[key as keyof this] != null;
-
- if (!isConfigurable) { // Test if the property can be configured on the crawler
- throw new Error(`${extension.name} tries to set property "${key}" that is not configurable on CheerioCrawler instance.`);
- }
-
- if (!isSameType && exists) { // Assuming that extensions will only add up configuration
- throw new Error(
- `${extension.name} tries to set property of different type "${extensionType}". "CheerioCrawler.${key}: ${originalType}".`,
- );
- }
-
- this.log.warning(`${extension.name} is overriding "CheerioCrawler.${key}: ${originalType}" with ${value}.`);
-
- this[key as keyof this] = value as this[keyof this];
- }
+ // eslint-disable-next-line @typescript-eslint/no-useless-constructor
+ constructor(options?: CheerioCrawlerOptions, config?: Configuration) {
+ super(options, config);
}
- /**
- * Wrapper around requestHandler that opens and closes pages etc.
- */
- protected override async _runRequestHandler(crawlingContext: CheerioCrawlingContext) {
- const { request, session } = crawlingContext;
-
- if (this.proxyConfiguration) {
- const sessionId = session ? session.id : undefined;
- crawlingContext.proxyInfo = await this.proxyConfiguration.newProxyInfo(sessionId);
- }
- if (!request.skipNavigation) {
- await this._handleNavigation(crawlingContext);
- tryCancel();
-
- const { dom, isXml, body, contentType, response } = await this._parseResponse(request, crawlingContext.response!);
- tryCancel();
-
- if (this.useSessionPool) {
- this._throwOnBlockedRequest(session!, response.statusCode!);
- }
-
- if (this.persistCookiesPerSession) {
- session!.setCookiesFromResponse(response);
- }
-
- request.loadedUrl = response.url;
-
- const $ = dom
- ? cheerio.load(dom as string, {
- xmlMode: isXml,
- // Recent versions of cheerio use parse5 as the HTML parser/serializer. It's more strict than htmlparser2
- // and not good for scraping. It also does not have a great streaming interface.
- // Here we tell cheerio to use htmlparser2 for serialization, otherwise the conflict produces weird errors.
- _useHtmlParser2: true,
- } as CheerioOptions)
- : null;
-
- crawlingContext.$ = $!;
- crawlingContext.contentType = contentType;
- crawlingContext.response = response;
- crawlingContext.enqueueLinks = async (enqueueOptions) => {
+ protected override async _parseHTML(response: IncomingMessage, isXml: boolean, crawlingContext: CheerioCrawlingContext) {
+ const dom = await this._parseHtmlToDom(response);
+
+ const $ = cheerio.load(dom as string, {
+ xmlMode: isXml,
+ // Recent versions of cheerio use parse5 as the HTML parser/serializer. It's more strict than htmlparser2
+ // and not good for scraping. It also does not have a great streaming interface.
+ // Here we tell cheerio to use htmlparser2 for serialization, otherwise the conflict produces weird errors.
+ _useHtmlParser2: true,
+ } as CheerioOptions);
+
+ return {
+ dom,
+ $,
+ get body() {
+ return isXml ? $!.xml() : $!.html({ decodeEntities: false });
+ },
+ enqueueLinks: async (enqueueOptions?: CheerioCrawlerEnqueueLinksOptions) => {
return cheerioCrawlerEnqueueLinks({
options: enqueueOptions,
$,
@@ -559,245 +161,8 @@ export class CheerioCrawler extends BasicCrawler<CheerioCrawlingContext> {
originalRequestUrl: crawlingContext.request.url,
finalRequestUrl: crawlingContext.request.loadedUrl,
});
- };
-
- Object.defineProperty(crawlingContext, 'json', {
- get() {
- if (contentType.type !== APPLICATION_JSON_MIME_TYPE) return null;
- const jsonString = body!.toString(contentType.encoding);
- return JSON.parse(jsonString);
- },
- });
-
- Object.defineProperty(crawlingContext, 'body', {
- get() {
- // NOTE: For XML/HTML documents, we don't store the original body and only reconstruct it from Cheerio's DOM.
- // This is to save memory for high-concurrency crawls. The downside is that changes
- // made to DOM are reflected in the HTML, but we can live with that...
- if (dom) {
- return isXml ? $!.xml() : $!.html({ decodeEntities: false });
- }
- return body;
- },
- });
- }
-
- return addTimeoutToPromise(
- () => Promise.resolve(this.requestHandler(crawlingContext)),
- this.userRequestHandlerTimeoutMillis,
- `requestHandler timed out after ${this.userRequestHandlerTimeoutMillis / 1000} seconds.`,
- );
- }
-
- protected async _handleNavigation(crawlingContext: CheerioCrawlingContext) {
- const gotOptions = {} as OptionsInit;
- const { request, session } = crawlingContext;
- const preNavigationHooksCookies = this._getCookieHeaderFromRequest(request);
-
- // Execute pre navigation hooks before applying session pool cookies,
- // as they may also set cookies in the session
- await this._executeHooks(this.preNavigationHooks, crawlingContext, gotOptions);
- tryCancel();
-
- const postNavigationHooksCookies = this._getCookieHeaderFromRequest(request);
-
- this._applyCookies(crawlingContext, gotOptions, preNavigationHooksCookies, postNavigationHooksCookies);
-
- const proxyUrl = crawlingContext.proxyInfo?.url;
-
- crawlingContext.response = await addTimeoutToPromise(
- () => this._requestFunction({ request, session, proxyUrl, gotOptions }),
- this.navigationTimeoutMillis,
- `request timed out after ${this.navigationTimeoutMillis / 1000} seconds.`,
- );
- tryCancel();
-
- await this._executeHooks(this.postNavigationHooks, crawlingContext, gotOptions);
- tryCancel();
- }
-
- /**
- * Sets the cookie header to `gotOptions` based on the provided request and session headers, as well as any changes that occurred due to hooks.
- */
- private _applyCookies({ session, request }: CrawlingContext, gotOptions: OptionsInit, preHookCookies: string, postHookCookies: string) {
- const sessionCookie = session?.getCookieString(request.url) ?? '';
- let alteredGotOptionsCookies = (gotOptions.headers?.Cookie || gotOptions.headers?.cookie || '');
-
- if (gotOptions.headers?.Cookie && gotOptions.headers?.cookie) {
- const {
- Cookie: upperCaseHeader,
- cookie: lowerCaseHeader,
- } = gotOptions.headers;
-
- // eslint-disable-next-line max-len
- this.log.warning(`Encountered mixed casing for the cookie headers in the got options for request ${request.url} (${request.id}). Their values will be merged`);
-
- const sourceCookies = [];
-
- if (Array.isArray(lowerCaseHeader)) {
- sourceCookies.push(...lowerCaseHeader);
- } else {
- sourceCookies.push(lowerCaseHeader);
- }
-
- if (Array.isArray(upperCaseHeader)) {
- sourceCookies.push(...upperCaseHeader);
- } else {
- sourceCookies.push(upperCaseHeader);
- }
-
- alteredGotOptionsCookies = mergeCookies(request.url, sourceCookies);
- }
-
- const sourceCookies = [
- sessionCookie,
- preHookCookies,
- ];
-
- if (Array.isArray(alteredGotOptionsCookies)) {
- sourceCookies.push(...alteredGotOptionsCookies);
- } else {
- sourceCookies.push(alteredGotOptionsCookies);
- }
-
- sourceCookies.push(postHookCookies);
-
- const mergedCookie = mergeCookies(request.url, sourceCookies);
-
- gotOptions.headers ??= {};
- Reflect.deleteProperty(gotOptions.headers, 'Cookie');
- Reflect.deleteProperty(gotOptions.headers, 'cookie');
- gotOptions.headers.Cookie = mergedCookie;
- }
-
- /**
- * Function to make the HTTP request. It performs optimizations
- * on the request such as only downloading the request body if the
- * received content type matches text/html, application/xml, application/xhtml+xml.
- */
- protected async _requestFunction({ request, session, proxyUrl, gotOptions }: RequestFunctionOptions): Promise<IncomingMessage> {
- const opts = this._getRequestOptions(request, session, proxyUrl, gotOptions);
-
- try {
- return await this._requestAsBrowser(opts);
- } catch (e) {
- if (e instanceof TimeoutError) {
- this._handleRequestTimeout(session);
- return undefined as unknown as IncomingMessage;
- }
-
- throw e;
- }
- }
-
- /**
- * Encodes and parses response according to the provided content type
- */
- protected async _parseResponse(request: Request, responseStream: IncomingMessage) {
- const { statusCode } = responseStream;
- const { type, charset } = parseContentTypeFromResponse(responseStream);
- const { response, encoding } = this._encodeResponse(request, responseStream, charset);
- const contentType = { type, encoding };
-
- if (statusCode! >= 500) {
- const body = await readStreamToString(response, encoding);
-
- // Errors are often sent as JSON, so attempt to parse them,
- // despite Accept header being set to text/html.
- if (type === APPLICATION_JSON_MIME_TYPE) {
- const errorResponse = JSON.parse(body);
- let { message } = errorResponse;
- if (!message) message = util.inspect(errorResponse, { depth: 1, maxArrayLength: 10 });
- throw new Error(`${statusCode} - ${message}`);
- }
-
- // It's not a JSON, so it's probably some text. Get the first 100 chars of it.
- throw new Error(`${statusCode} - Internal Server Error: ${body.substr(0, 100)}`);
- } else if (HTML_AND_XML_MIME_TYPES.includes(type)) {
- const dom = await this._parseHtmlToDom(response);
- return ({ dom, isXml: type.includes('xml'), response, contentType });
- } else {
- const body = await concatStreamToBuffer(response);
- return { body, response, contentType };
- }
- }
-
- /**
- * Combines the provided `requestOptions` with mandatory (non-overridable) values.
- */
- protected _getRequestOptions(request: Request, session?: Session, proxyUrl?: string, gotOptions?: OptionsInit) {
- const requestOptions: OptionsInit & { isStream: true } = {
- url: request.url,
- method: request.method as Method,
- proxyUrl,
- timeout: { request: this.navigationTimeoutMillis },
- sessionToken: session,
- ...gotOptions,
- headers: { ...request.headers, ...gotOptions?.headers },
- https: {
- ...gotOptions?.https,
- rejectUnauthorized: !this.ignoreSslErrors,
},
- isStream: true,
};
-
- // Delete any possible lowercased header for cookie as they are merged in _applyCookies under the uppercase Cookie header
- Reflect.deleteProperty(requestOptions.headers!, 'cookie');
-
- // TODO this is incorrect, the check for man in the middle needs to be done
- // on individual proxy level, not on the `proxyConfiguration` level,
- // because users can use normal + MITM proxies in a single configuration.
- // Disable SSL verification for MITM proxies
- if (this.proxyConfiguration && this.proxyConfiguration.isManInTheMiddle) {
- requestOptions.https = {
- ...requestOptions.https,
- rejectUnauthorized: false,
- };
- }
-
- if (/PATCH|POST|PUT/.test(request.method)) requestOptions.body = request.payload;
-
- return requestOptions;
- }
-
- protected _encodeResponse(request: Request, response: IncomingMessage, encoding: BufferEncoding): {
- encoding: BufferEncoding;
- response: IncomingMessage;
- } {
- if (this.forceResponseEncoding) {
- encoding = this.forceResponseEncoding as BufferEncoding;
- } else if (!encoding && this.suggestResponseEncoding) {
- encoding = this.suggestResponseEncoding as BufferEncoding;
- }
-
- // Fall back to utf-8 if we still don't have encoding.
- const utf8 = 'utf8';
- if (!encoding) return { response, encoding: utf8 };
-
- // This means that the encoding is one of Node.js supported
- // encodings and we don't need to re-encode it.
- if (Buffer.isEncoding(encoding)) return { response, encoding };
-
- // Try to re-encode a variety of unsupported encodings to utf-8
- if (iconv.encodingExists(encoding)) {
- const encodeStream = iconv.encodeStream(utf8);
- const decodeStream = iconv.decodeStream(encoding).on('error', (err) => encodeStream.emit('error', err));
- response.on('error', (err: Error) => decodeStream.emit('error', err));
- const encodedResponse = response.pipe(decodeStream).pipe(encodeStream) as NodeJS.ReadWriteStream & {
- statusCode?: number;
- headers: IncomingHttpHeaders;
- url?: string;
- };
- encodedResponse.statusCode = response.statusCode;
- encodedResponse.headers = response.headers;
- encodedResponse.url = response.url;
- return {
- response: encodedResponse as any,
- encoding: utf8,
- };
- }
-
- throw new Error(`Resource ${request.url} served with unsupported charset/encoding: ${encoding}`);
}
protected async _parseHtmlToDom(response: IncomingMessage) {
@@ -813,63 +178,11 @@ export class CheerioCrawler extends BasicCrawler<CheerioCrawlingContext> {
.pipe(parser);
});
}
-
- /**
- * Checks and extends supported mime types
- */
- protected _extendSupportedMimeTypes(additionalMimeTypes: (string | RequestLike | ResponseLike)[]) {
- additionalMimeTypes.forEach((mimeType) => {
- try {
- const parsedType = contentTypeParser.parse(mimeType);
- this.supportedMimeTypes.add(parsedType.type);
- } catch (err) {
- throw new Error(`Can not parse mime type ${mimeType} from "options.additionalMimeTypes".`);
- }
- });
- }
-
- /**
- * Handles timeout request
- */
- protected _handleRequestTimeout(session?: Session) {
- session?.markBad();
- throw new Error(`request timed out after ${this.requestHandlerTimeoutMillis / 1000} seconds.`);
- }
-
- private _abortDownloadOfBody(request: Request, response: IncomingMessage) {
- const { statusCode } = response;
- const { type } = parseContentTypeFromResponse(response);
-
- if (statusCode === 406) {
- request.noRetry = true;
- throw new Error(`Resource ${request.url} is not available in the format requested by the Accept header. Skipping resource.`);
- }
-
- if (!this.supportedMimeTypes.has(type) && statusCode! < 500) {
- request.noRetry = true;
- throw new Error(`Resource ${request.url} served Content-Type ${type}, `
- + `but only ${Array.from(this.supportedMimeTypes).join(', ')} are allowed. Skipping resource.`);
- }
- }
-
- /**
- * @internal wraps public utility for mocking purposes
- */
- private _requestAsBrowser = (options: OptionsInit & { isStream: true }) => {
- return new Promise<IncomingMessage>((resolve, reject) => {
- const stream = gotScraping(options);
-
- stream.on('error', reject);
- stream.on('response', () => {
- resolve(addResponsePropertiesToStream(stream));
- });
- });
- };
}
interface EnqueueLinksInternalOptions {
options?: CheerioCrawlerEnqueueLinksOptions;
- $: CheerioRoot | null;
+ $: cheerio.CheerioAPI | null;
requestQueue: RequestQueue;
originalRequestUrl: string;
finalRequestUrl?: string;
@@ -898,18 +211,11 @@ export async function cheerioCrawlerEnqueueLinks({ options, $, requestQueue, ori
});
}
-interface RequestFunctionOptions {
- request: Request;
- session?: Session;
- proxyUrl?: string;
- gotOptions: OptionsInit;
-}
-
/**
* Extracts URLs from a given Cheerio object.
* @ignore
*/
-function extractUrlsFromCheerio($: CheerioRoot, selector: string, baseUrl?: string): string[] {
+function extractUrlsFromCheerio($: cheerio.CheerioAPI, selector: string, baseUrl?: string): string[] {
return $(selector)
.map((_i, el) => $(el).attr('href'))
.get()
@@ -935,44 +241,6 @@ function extractUrlsFromCheerio($: CheerioRoot, selector: string, baseUrl?: stri
.filter((href) => !!href) as string[];
}
-/**
- * The stream object returned from got does not have the below properties.
- * At the same time, you can't read data directly from the response stream,
- * because they won't get emitted unless you also read from the primary
- * got stream. To be able to work with only one stream, we move the expected props
- * from the response stream to the got stream.
- * @internal
- */
-function addResponsePropertiesToStream(stream: GotRequest) {
- const properties = [
- 'statusCode', 'statusMessage', 'headers',
- 'complete', 'httpVersion', 'rawHeaders',
- 'rawTrailers', 'trailers', 'url',
- 'request',
- ];
-
- const response = stream.response!;
-
- response.on('end', () => {
- // @ts-expect-error
- Object.assign(stream.rawTrailers, response.rawTrailers);
- // @ts-expect-error
- Object.assign(stream.trailers, response.trailers);
-
- // @ts-expect-error
- stream.complete = response.complete;
- });
-
- for (const prop of properties) {
- if (!(prop in stream)) {
- // @ts-expect-error
- stream[prop] = response[prop as keyof IncomingMessage];
- }
- }
-
- return stream as unknown as IncomingMessage;
-}
-
/**
* Creates new {@apilink Router} instance that works based on request labels.
* This instance can then serve as a `requestHandler` of your {@apilink CheerioCrawler}.
diff --git a/packages/core/README.md b/packages/core/README.md
index 750ac27a1..9c945738b 100644
--- a/packages/core/README.md
+++ b/packages/core/README.md
@@ -6,6 +6,7 @@ The [`crawlee`](https://www.npmjs.com/package/crawlee) package consists of sever
- `@crawlee/core`: the base for all the crawler implementations, also contains things like `Request`, `RequestQueue`, `RequestList` or `Dataset` classes
- `@crawlee/basic`: exports `BasicCrawler`
+- `@crawlee/http`: exports `HttpCrawler` (which is used for creating `@crawlee/cheerio`)
- `@crawlee/cheerio`: exports `CheerioCrawler`
- `@crawlee/browser`: exports `BrowserCrawler` (which is used for creating `@crawlee/playwright` and `@crawlee/puppeteer`)
- `@crawlee/playwright`: exports `PlaywrightCrawler`
diff --git a/packages/crawlee/src/index.ts b/packages/crawlee/src/index.ts
index 59bcdcdfd..a5d1e6ef3 100644
--- a/packages/crawlee/src/index.ts
+++ b/packages/crawlee/src/index.ts
@@ -9,6 +9,7 @@ export * from '@crawlee/core';
export * from '@crawlee/utils';
export * from '@crawlee/basic';
export * from '@crawlee/browser';
+export * from '@crawlee/http';
export * from '@crawlee/cheerio';
export * from '@crawlee/puppeteer';
export * from '@crawlee/playwright';
diff --git a/packages/http-crawler/.npmignore b/packages/http-crawler/.npmignore
new file mode 100644
index 000000000..ada367d72
--- /dev/null
+++ b/packages/http-crawler/.npmignore
@@ -0,0 +1,6 @@
+node_modules
+src
+test
+coverage
+apify_storage
+tsconfig.*
diff --git a/packages/http-crawler/README.md b/packages/http-crawler/README.md
new file mode 100644
index 000000000..00ad889de
--- /dev/null
+++ b/packages/http-crawler/README.md
@@ -0,0 +1,47 @@
+# `@crawlee/http`
+
+Provides a framework for the parallel crawling of web pages using plain HTTP requests. The URLs to crawl are fed either from a static list of URLs or from a dynamic queue of URLs enabling recursive crawling of websites.
+
+It is very fast and efficient on data bandwidth. However, if the target website requires JavaScript to display the content, you might need to use {[PuppeteerCrawler](https://crawlee.dev/api/puppeteer-crawler/class/PuppeteerCrawler) or [PlaywrightCrawler](https://crawlee.dev/api/playwright-crawler/class/PlaywrightCrawler) instead, because it loads the pages using full-featured headless Chrome browser. **This crawler downloads each URL using a plain HTTP request and doesn't do any HTML parsing.**
+
+The source URLs are represented using [Request](https://crawlee.dev/api/core/class/Request) objects that are fed from [RequestList](https://crawlee.dev/api/core/class/RequestList) or [RequestQueue](https://crawlee.dev/api/core/class/RequestQueue) instances provided by the [HttpCrawlerOptions.requestList](https://crawlee.dev/api/http-crawler/interface/HttpCrawlerOptions#requestList) or [HttpCrawlerOptions.requestQueue](https://crawlee.dev/api/http-crawler/interface/HttpCrawlerOptions#requestQueue) constructor options, respectively.
+
+If both [HttpCrawlerOptions.requestList](https://crawlee.dev/api/http-crawler/interface/HttpCrawlerOptions#requestList) and [HttpCrawlerOptions.requestQueue](https://crawlee.dev/api/http-crawler/interface/HttpCrawlerOptions#requestQueue) are used, the instance first processes URLs from the [RequestList](https://crawlee.dev/api/core/class/RequestList) and automatically enqueues all of them to [RequestQueue](https://crawlee.dev/api/core/class/RequestQueue) before it starts their processing. This ensures that a single URL is not crawled multiple times.
+
+The crawler finishes when there are no more [Request](https://crawlee.dev/api/core/class/Request) objects to crawl.
+
+We can use the `preNavigationHooks` to adjust `gotOptions`:
+
+```javascript
+preNavigationHooks: [
+ (crawlingContext, gotOptions) => {
+ // ...
+ },
+]
+```
+
+By default, `HttpCrawler` only processes web pages with the `text/html` and `application/xhtml+xml` MIME content types (as reported by the `Content-Type` HTTP header), and skips pages with other content types. If you want the crawler to process other content types, use the [HttpCrawlerOptions.additionalMimeTypes](https://crawlee.dev/api/http-crawler/interface/HttpCrawlerOptions#additionalMimeTypes) constructor option. Beware that the parsing behavior differs for HTML, XML, JSON and other types of content. For more details, see [HttpCrawlerOptions.requestHandler](https://crawlee.dev/api/http-crawler/interface/HttpCrawlerOptions#requestHandler).
+
+New requests are only dispatched when there is enough free CPU and memory available, using the functionality provided by the [AutoscaledPool](https://crawlee.dev/api/core/class/AutoscaledPool) class. All [AutoscaledPool](https://crawlee.dev/api/core/class/AutoscaledPool) configuration options can be passed to the `autoscaledPoolOptions` parameter of the `HttpCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency` [AutoscaledPool](https://crawlee.dev/api/core/class/AutoscaledPool) options are available directly in the `HttpCrawler` constructor.
+
+## Example usage
+
+```javascript
+import { HttpCrawler, Dataset } from '@crawlee/http';
+
+const crawler = new HttpCrawler({
+ requestList,
+ async requestHandler({ request, response, body, contentType }) {
+ // Save the data to dataset.
+ await Dataset.pushData({
+ url: request.url,
+ html: body,
+ });
+ },
+});
+
+await crawler.run([
+ 'http://www.example.com/page-1',
+ 'http://www.example.com/page-2',
+]);
+```
diff --git a/packages/http-crawler/package.json b/packages/http-crawler/package.json
new file mode 100644
index 000000000..21cfe707e
--- /dev/null
+++ b/packages/http-crawler/package.json
@@ -0,0 +1,67 @@
+{
+ "name": "@crawlee/http",
+ "version": "3.0.3",
+ "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.",
+ "engines": {
+ "node": ">=16.0.0"
+ },
+ "main": "./dist/index.js",
+ "module": "./dist/index.mjs",
+ "types": "./dist/index.d.ts",
+ "exports": {
+ ".": {
+ "import": "./dist/index.mjs",
+ "require": "./dist/index.js",
+ "types": "./dist/index.d.ts"
+ },
+ "./package.json": "./package.json"
+ },
+ "keywords": [
+ "apify",
+ "headless",
+ "chrome",
+ "puppeteer",
+ "crawler",
+ "scraper"
+ ],
+ "author": {
+ "name": "Apify",
+ "email": "[email protected]",
+ "url": "https://apify.com"
+ },
+ "contributors": [
+ "Jan Curn <[email protected]>",
+ "Marek Trunkat <[email protected]>",
+ "Ondra Urban <[email protected]>"
+ ],
+ "license": "Apache-2.0",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/apify/crawlee"
+ },
+ "bugs": {
+ "url": "https://github.com/apify/crawlee/issues"
+ },
+ "homepage": "https://crawlee.dev",
+ "scripts": {
+ "build": "npm run clean && npm run compile && npm run copy",
+ "clean": "rimraf ./dist",
+ "compile": "tsc -p tsconfig.build.json && gen-esm-wrapper ./dist/index.js ./dist/index.mjs",
+ "copy": "ts-node -T ../../scripts/copy.ts"
+ },
+ "publishConfig": {
+ "access": "public"
+ },
+ "dependencies": {
+ "@apify/timeout": "^0.3.0",
+ "@apify/utilities": "^2.0.0",
+ "@crawlee/basic": "^3.0.3",
+ "@crawlee/types": "^3.0.3",
+ "@types/content-type": "^1.1.5",
+ "content-type": "^1.0.4",
+ "got-scraping": "^3.2.9",
+ "iconv-lite": "^0.6.3",
+ "mime-types": "^2.1.35",
+ "ow": "^0.28.1"
+ }
+}
diff --git a/packages/http-crawler/src/index.ts b/packages/http-crawler/src/index.ts
new file mode 100644
index 000000000..b46fb9c47
--- /dev/null
+++ b/packages/http-crawler/src/index.ts
@@ -0,0 +1,2 @@
+export * from '@crawlee/basic';
+export * from './internals/http-crawler';
diff --git a/packages/http-crawler/src/internals/http-crawler.ts b/packages/http-crawler/src/internals/http-crawler.ts
new file mode 100644
index 000000000..7218172e7
--- /dev/null
+++ b/packages/http-crawler/src/internals/http-crawler.ts
@@ -0,0 +1,845 @@
+import { addTimeoutToPromise, tryCancel } from '@apify/timeout';
+import { concatStreamToBuffer, readStreamToString } from '@apify/utilities';
+import type {
+ AutoscaledPoolOptions,
+ BasicCrawlerOptions,
+ ErrorHandler,
+ RequestHandler,
+ CrawlingContext,
+ ProxyConfiguration,
+ Request,
+ Session,
+} from '@crawlee/basic';
+import {
+ BasicCrawler,
+ BASIC_CRAWLER_TIMEOUT_BUFFER_SECS,
+ CrawlerExtension,
+ mergeCookies,
+ Router,
+ validators,
+ Configuration,
+} from '@crawlee/basic';
+import type { Awaitable, Dictionary } from '@crawlee/types';
+import type { RequestLike, ResponseLike } from 'content-type';
+import contentTypeParser from 'content-type';
+import mime from 'mime-types';
+import type { OptionsInit, Method, Request as GotRequest, Response as GotResponse, GotOptionsInit } from 'got-scraping';
+import { gotScraping, TimeoutError } from 'got-scraping';
+import { extname } from 'path';
+import type { IncomingHttpHeaders, IncomingMessage } from 'node:http';
+import iconv from 'iconv-lite';
+import ow from 'ow';
+import util from 'node:util';
+
+/**
+ * Default mime types, which HttpScraper supports.
+ */
+const HTML_AND_XML_MIME_TYPES = ['text/html', 'text/xml', 'application/xhtml+xml', 'application/xml'];
+const APPLICATION_JSON_MIME_TYPE = 'application/json';
+const HTTP_OPTIMIZED_AUTOSCALED_POOL_OPTIONS: AutoscaledPoolOptions = {
+ desiredConcurrency: 10,
+ snapshotterOptions: {
+ eventLoopSnapshotIntervalSecs: 2,
+ maxBlockedMillis: 100,
+ },
+ systemStatusOptions: {
+ maxEventLoopOverloadedRatio: 0.7,
+ },
+};
+
+export type HttpErrorHandler<
+ UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
+ JSONData extends Dictionary = Dictionary,
+ > = ErrorHandler<HttpCrawlingContext<UserData, JSONData>>;
+
+export interface HttpCrawlerOptions<Context extends InternalHttpCrawlingContext = InternalHttpCrawlingContext> extends BasicCrawlerOptions<Context> {
+ /**
+ * An alias for {@apilink HttpCrawlerOptions.requestHandler}
+ * Soon to be removed, use `requestHandler` instead.
+ * @deprecated
+ */
+ handlePageFunction?: HttpCrawlerOptions<Context>['requestHandler'];
+
+ /**
+ * Timeout in which the HTTP request to the resource needs to finish, given in seconds.
+ */
+ navigationTimeoutSecs?: number;
+
+ /**
+ * If set to true, SSL certificate errors will be ignored.
+ */
+ ignoreSslErrors?: boolean;
+
+ /**
+ * If set, this crawler will be configured for all connections to use
+ * [Apify Proxy](https://console.apify.com/proxy) or your own Proxy URLs provided and rotated according to the configuration.
+ * For more information, see the [documentation](https://docs.apify.com/proxy).
+ */
+ proxyConfiguration?: ProxyConfiguration;
+
+ /**
+ * Async functions that are sequentially evaluated before the navigation. Good for setting additional cookies
+ * or browser properties before navigation. The function accepts two parameters, `crawlingContext` and `gotOptions`,
+ * which are passed to the `requestAsBrowser()` function the crawler calls to navigate.
+ * Example:
+ * ```
+ * preNavigationHooks: [
+ * async (crawlingContext, gotOptions) => {
+ * // ...
+ * },
+ * ]
+ * ```
+ */
+ preNavigationHooks?: InternalHttpHook<Context>[];
+
+ /**
+ * Async functions that are sequentially evaluated after the navigation. Good for checking if the navigation was successful.
+ * The function accepts `crawlingContext` as the only parameter.
+ * Example:
+ * ```
+ * postNavigationHooks: [
+ * async (crawlingContext) => {
+ * // ...
+ * },
+ * ]
+ * ```
+ */
+ postNavigationHooks?: InternalHttpHook<Context>[];
+
+ /**
+ * An array of [MIME types](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types)
+ * you want the crawler to load and process. By default, only `text/html` and `application/xhtml+xml` MIME types are supported.
+ */
+ additionalMimeTypes?: string[];
+
+ /**
+ * By default this crawler will extract correct encoding from the HTTP response headers.
+ * Sadly, there are some websites which use invalid headers. Those are encoded using the UTF-8 encoding.
+ * If those sites actually use a different encoding, the response will be corrupted. You can use
+ * `suggestResponseEncoding` to fall back to a certain encoding, if you know that your target website uses it.
+ * To force a certain encoding, disregarding the response headers, use {@apilink HttpCrawlerOptions.forceResponseEncoding}
+ * ```
+ * // Will fall back to windows-1250 encoding if none found
+ * suggestResponseEncoding: 'windows-1250'
+ * ```
+ */
+ suggestResponseEncoding?: string;
+
+ /**
+ * By default this crawler will extract correct encoding from the HTTP response headers. Use `forceResponseEncoding`
+ * to force a certain encoding, disregarding the response headers.
+ * To only provide a default for missing encodings, use {@apilink HttpCrawlerOptions.suggestResponseEncoding}
+ * ```
+ * // Will force windows-1250 encoding even if headers say otherwise
+ * forceResponseEncoding: 'windows-1250'
+ * ```
+ */
+ forceResponseEncoding?: string;
+
+ /**
+ * Automatically saves cookies to Session. Works only if Session Pool is used.
+ *
+ * It parses cookie from response "set-cookie" header saves or updates cookies for session and once the session is used for next request.
+ * It passes the "Cookie" header to the request with the session cookies.
+ */
+ persistCookiesPerSession?: boolean;
+}
+
+/**
+ * @internal
+ */
+export type InternalHttpHook<Context> = (
+ crawlingContext: Context,
+ gotOptions: OptionsInit,
+) => Awaitable<void>;
+
+export type HttpHook<
+ UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
+ JSONData extends Dictionary = Dictionary,
+> = InternalHttpHook<HttpCrawlingContext<UserData, JSONData>>;
+
+/**
+ * @internal
+ */
+export interface InternalHttpCrawlingContext<
+ UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
+ JSONData extends Dictionary = Dictionary,
+ Crawler = HttpCrawler<any>
+ > extends CrawlingContext<UserData> {
+ /**
+ * The request body of the web page.
+ * The type depends on the `Content-Type` header of the web page:
+ * - String for `text/html`, `application/xhtml+xml`, `application/xml` MIME content types
+ * - Buffer for others MIME content types
+ */
+ body: (string | Buffer);
+
+ /**
+ * The parsed object from JSON string if the response contains the content type application/json.
+ */
+ json: JSONData;
+
+ /**
+ * Parsed `Content-Type header: { type, encoding }`.
+ */
+ contentType: { type: string; encoding: BufferEncoding };
+ crawler: Crawler;
+ response: IncomingMessage;
+ sendRequest: (overrideOptions?: Partial<GotOptionsInit>) => Promise<GotResponse<string>>;
+}
+
+export interface HttpCrawlingContext<UserData = any, JSONData = any>
+ extends InternalHttpCrawlingContext<UserData, JSONData, HttpCrawler<HttpCrawlingContext<UserData, JSONData>>> {}
+
+export type HttpRequestHandler<
+ UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
+ JSONData extends Dictionary = Dictionary,
+ > = RequestHandler<HttpCrawlingContext<UserData, JSONData>>;
+
+/**
+ * Provides a framework for the parallel crawling of web pages using plain HTTP requests.
+ * The URLs to crawl are fed either from a static list of URLs
+ * or from a dynamic queue of URLs enabling recursive crawling of websites.
+ *
+ * It is very fast and efficient on data bandwidth. However, if the target website requires JavaScript
+ * to display the content, you might need to use {@apilink PuppeteerCrawler} or {@apilink PlaywrightCrawler} instead,
+ * because it loads the pages using full-featured headless Chrome browser.
+ *
+ * This crawler downloads each URL using a plain HTTP request and doesn't do any HTML parsing.
+ *
+ * The source URLs are represented using {@apilink Request} objects that are fed from
+ * {@apilink RequestList} or {@apilink RequestQueue} instances provided by the {@apilink HttpCrawlerOptions.requestList}
+ * or {@apilink HttpCrawlerOptions.requestQueue} constructor options, respectively.
+ *
+ * If both {@apilink HttpCrawlerOptions.requestList} and {@apilink HttpCrawlerOptions.requestQueue} are used,
+ * the instance first processes URLs from the {@apilink RequestList} and automatically enqueues all of them
+ * to {@apilink RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.
+ *
+ * The crawler finishes when there are no more {@apilink Request} objects to crawl.
+ *
+ * We can use the `preNavigationHooks` to adjust `gotOptions`:
+ *
+ * ```javascript
+ * preNavigationHooks: [
+ * (crawlingContext, gotOptions) => {
+ * // ...
+ * },
+ * ]
+ * ```
+ *
+ * By default, this crawler only processes web pages with the `text/html`
+ * and `application/xhtml+xml` MIME content types (as reported by the `Content-Type` HTTP header),
+ * and skips pages with other content types. If you want the crawler to process other content types,
+ * use the {@apilink HttpCrawlerOptions.additionalMimeTypes} constructor option.
+ * Beware that the parsing behavior differs for HTML, XML, JSON and other types of content.
+ * For details, see {@apilink HttpCrawlerOptions.requestHandler}.
+ *
+ * New requests are only dispatched when there is enough free CPU and memory available,
+ * using the functionality provided by the {@apilink AutoscaledPool} class.
+ * All {@apilink AutoscaledPool} configuration options can be passed to the `autoscaledPoolOptions`
+ * parameter of the constructor. For user convenience, the `minConcurrency` and `maxConcurrency`
+ * {@apilink AutoscaledPool} options are available directly in the constructor.
+ *
+ * **Example usage:**
+ *
+ * ```javascript
+ * import { HttpCrawler, Dataset } from '@crawlee/http';
+ *
+ * const crawler = new HttpCrawler({
+ * requestList,
+ * async requestHandler({ request, response, body, contentType }) {
+ * // Save the data to dataset.
+ * await Dataset.pushData({
+ * url: request.url,
+ * html: body,
+ * });
+ * },
+ * });
+ *
+ * await crawler.run([
+ * 'http://www.example.com/page-1',
+ * 'http://www.example.com/page-2',
+ * ]);
+ * ```
+ * @category Crawlers
+ */
+export class HttpCrawler<Context extends InternalHttpCrawlingContext<any, any, HttpCrawler<Context>>> extends BasicCrawler<Context> {
+ /**
+ * A reference to the underlying {@apilink ProxyConfiguration} class that manages the crawler's proxies.
+ * Only available if used by the crawler.
+ */
+ proxyConfiguration?: ProxyConfiguration;
+
+ protected userRequestHandlerTimeoutMillis: number;
+ protected preNavigationHooks: InternalHttpHook<Context>[];
+ protected postNavigationHooks: InternalHttpHook<Context>[];
+ protected persistCookiesPerSession: boolean;
+ protected navigationTimeoutMillis: number;
+ protected ignoreSslErrors: boolean;
+ protected suggestResponseEncoding?: string;
+ protected forceResponseEncoding?: string;
+ protected readonly supportedMimeTypes: Set<string>;
+
+ protected static override optionsShape = {
+ ...BasicCrawler.optionsShape,
+ handlePageFunction: ow.optional.function,
+
+ navigationTimeoutSecs: ow.optional.number,
+ ignoreSslErrors: ow.optional.boolean,
+ additionalMimeTypes: ow.optional.array.ofType(ow.string),
+ suggestResponseEncoding: ow.optional.string,
+ forceResponseEncoding: ow.optional.string,
+ proxyConfiguration: ow.optional.object.validate(validators.proxyConfiguration),
+ persistCookiesPerSession: ow.optional.boolean,
+
+ preNavigationHooks: ow.optional.array,
+ postNavigationHooks: ow.optional.array,
+ };
+
+ /**
+ * All `HttpCrawlerOptions` parameters are passed via an options object.
+ */
+ constructor(options: HttpCrawlerOptions<Context> = {}, override readonly config = Configuration.getGlobalConfig()) {
+ ow(options, 'HttpCrawlerOptions', ow.object.exactShape(HttpCrawler.optionsShape));
+
+ const {
+ requestHandler,
+ handlePageFunction,
+
+ requestHandlerTimeoutSecs = 60,
+ navigationTimeoutSecs = 30,
+ ignoreSslErrors = true,
+ additionalMimeTypes = [],
+ suggestResponseEncoding,
+ forceResponseEncoding,
+ proxyConfiguration,
+ persistCookiesPerSession,
+ preNavigationHooks = [],
+ postNavigationHooks = [],
+
+ // Ignored
+ handleRequestFunction,
+
+ // BasicCrawler
+ autoscaledPoolOptions = HTTP_OPTIMIZED_AUTOSCALED_POOL_OPTIONS,
+ ...basicCrawlerOptions
+ } = options;
+
+ super({
+ ...basicCrawlerOptions,
+ requestHandler,
+ autoscaledPoolOptions,
+ // We need to add some time for internal functions to finish,
+ // but not too much so that we would stall the crawler.
+ requestHandlerTimeoutSecs: navigationTimeoutSecs + requestHandlerTimeoutSecs + BASIC_CRAWLER_TIMEOUT_BUFFER_SECS,
+ }, config);
+
+ this._handlePropertyNameChange({
+ newName: 'requestHandler',
+ oldName: 'handlePageFunction',
+ propertyKey: 'requestHandler',
+ newProperty: requestHandler,
+ oldProperty: handlePageFunction,
+ allowUndefined: true,
+ });
+
+ if (!this.requestHandler) {
+ this.requestHandler = this.router;
+ }
+
+ // Cookies should be persisted per session only if session pool is used
+ if (!this.useSessionPool && persistCookiesPerSession) {
+ throw new Error('You cannot use "persistCookiesPerSession" without "useSessionPool" set to true.');
+ }
+
+ this.supportedMimeTypes = new Set([...HTML_AND_XML_MIME_TYPES, APPLICATION_JSON_MIME_TYPE]);
+ if (additionalMimeTypes.length) this._extendSupportedMimeTypes(additionalMimeTypes);
+
+ if (suggestResponseEncoding && forceResponseEncoding) {
+ this.log.warning('Both forceResponseEncoding and suggestResponseEncoding options are set. Using forceResponseEncoding.');
+ }
+
+ this.userRequestHandlerTimeoutMillis = requestHandlerTimeoutSecs * 1000;
+ this.navigationTimeoutMillis = navigationTimeoutSecs * 1000;
+ this.ignoreSslErrors = ignoreSslErrors;
+ this.suggestResponseEncoding = suggestResponseEncoding;
+ this.forceResponseEncoding = forceResponseEncoding;
+ this.proxyConfiguration = proxyConfiguration;
+ this.preNavigationHooks = preNavigationHooks;
+ this.postNavigationHooks = [
+ ({ request, response }) => this._abortDownloadOfBody(request, response!),
+ ...postNavigationHooks,
+ ];
+
+ if (this.useSessionPool) {
+ this.persistCookiesPerSession = persistCookiesPerSession ?? true;
+ } else {
+ this.persistCookiesPerSession = false;
+ }
+ }
+
+ /**
+ * **EXPERIMENTAL**
+ * Function for attaching CrawlerExtensions such as the Unblockers.
+ * @param extension Crawler extension that overrides the crawler configuration.
+ */
+ use(extension: CrawlerExtension) {
+ ow(extension, ow.object.instanceOf(CrawlerExtension));
+
+ const className = this.constructor.name;
+
+ const extensionOptions = extension.getCrawlerOptions();
+
+ for (const [key, value] of Object.entries(extensionOptions)) {
+ const isConfigurable = this.hasOwnProperty(key);
+ const originalType = typeof this[key as keyof this];
+ const extensionType = typeof value; // What if we want to null something? It is really needed?
+ const isSameType = originalType === extensionType || value == null; // fast track for deleting keys
+ const exists = this[key as keyof this] != null;
+
+ if (!isConfigurable) { // Test if the property can be configured on the crawler
+ throw new Error(`${extension.name} tries to set property "${key}" that is not configurable on ${className} instance.`);
+ }
+
+ if (!isSameType && exists) { // Assuming that extensions will only add up configuration
+ throw new Error(
+ `${extension.name} tries to set property of different type "${extensionType}". "${className}.${key}: ${originalType}".`,
+ );
+ }
+
+ this.log.warning(`${extension.name} is overriding "${className}.${key}: ${originalType}" with ${value}.`);
+
+ this[key as keyof this] = value as this[keyof this];
+ }
+ }
+
+ /**
+ * Wrapper around requestHandler that opens and closes pages etc.
+ */
+ protected override async _runRequestHandler(crawlingContext: Context) {
+ const { request, session } = crawlingContext;
+
+ if (this.proxyConfiguration) {
+ const sessionId = session ? session.id : undefined;
+ crawlingContext.proxyInfo = await this.proxyConfiguration.newProxyInfo(sessionId);
+ }
+ if (!request.skipNavigation) {
+ await this._handleNavigation(crawlingContext);
+ tryCancel();
+
+ const parsed = await this._parseResponse(request, crawlingContext.response!, crawlingContext);
+ const response = parsed.response!;
+ const contentType = parsed.contentType!;
+ tryCancel();
+
+ if (this.useSessionPool) {
+ this._throwOnBlockedRequest(session!, response.statusCode!);
+ }
+
+ if (this.persistCookiesPerSession) {
+ session!.setCookiesFromResponse(response);
+ }
+
+ request.loadedUrl = response.url;
+
+ Object.assign(crawlingContext, parsed);
+
+ Object.defineProperty(crawlingContext, 'json', {
+ get() {
+ if (contentType.type !== APPLICATION_JSON_MIME_TYPE) return null;
+ const jsonString = parsed.body!.toString(contentType.encoding);
+ return JSON.parse(jsonString);
+ },
+ });
+ }
+
+ return addTimeoutToPromise(
+ () => Promise.resolve(this.requestHandler(crawlingContext)),
+ this.userRequestHandlerTimeoutMillis,
+ `requestHandler timed out after ${this.userRequestHandlerTimeoutMillis / 1000} seconds.`,
+ );
+ }
+
+ protected async _handleNavigation(crawlingContext: Context) {
+ const gotOptions = {} as OptionsInit;
+ const { request, session } = crawlingContext;
+ const preNavigationHooksCookies = this._getCookieHeaderFromRequest(request);
+
+ // Execute pre navigation hooks before applying session pool cookies,
+ // as they may also set cookies in the session
+ await this._executeHooks(this.preNavigationHooks, crawlingContext, gotOptions);
+ tryCancel();
+
+ const postNavigationHooksCookies = this._getCookieHeaderFromRequest(request);
+
+ this._applyCookies(crawlingContext, gotOptions, preNavigationHooksCookies, postNavigationHooksCookies);
+
+ const proxyUrl = crawlingContext.proxyInfo?.url;
+
+ crawlingContext.response = await addTimeoutToPromise(
+ () => this._requestFunction({ request, session, proxyUrl, gotOptions }),
+ this.navigationTimeoutMillis,
+ `request timed out after ${this.navigationTimeoutMillis / 1000} seconds.`,
+ );
+ tryCancel();
+
+ await this._executeHooks(this.postNavigationHooks, crawlingContext, gotOptions);
+ tryCancel();
+ }
+
+ /**
+ * Sets the cookie header to `gotOptions` based on the provided request and session headers, as well as any changes that occurred due to hooks.
+ */
+ private _applyCookies({ session, request }: CrawlingContext, gotOptions: OptionsInit, preHookCookies: string, postHookCookies: string) {
+ const sessionCookie = session?.getCookieString(request.url) ?? '';
+ let alteredGotOptionsCookies = (gotOptions.headers?.Cookie || gotOptions.headers?.cookie || '');
+
+ if (gotOptions.headers?.Cookie && gotOptions.headers?.cookie) {
+ const {
+ Cookie: upperCaseHeader,
+ cookie: lowerCaseHeader,
+ } = gotOptions.headers;
+
+ // eslint-disable-next-line max-len
+ this.log.warning(`Encountered mixed casing for the cookie headers in the got options for request ${request.url} (${request.id}). Their values will be merged`);
+
+ const sourceCookies = [];
+
+ if (Array.isArray(lowerCaseHeader)) {
+ sourceCookies.push(...lowerCaseHeader);
+ } else {
+ sourceCookies.push(lowerCaseHeader);
+ }
+
+ if (Array.isArray(upperCaseHeader)) {
+ sourceCookies.push(...upperCaseHeader);
+ } else {
+ sourceCookies.push(upperCaseHeader);
+ }
+
+ alteredGotOptionsCookies = mergeCookies(request.url, sourceCookies);
+ }
+
+ const sourceCookies = [
+ sessionCookie,
+ preHookCookies,
+ ];
+
+ if (Array.isArray(alteredGotOptionsCookies)) {
+ sourceCookies.push(...alteredGotOptionsCookies);
+ } else {
+ sourceCookies.push(alteredGotOptionsCookies);
+ }
+
+ sourceCookies.push(postHookCookies);
+
+ const mergedCookie = mergeCookies(request.url, sourceCookies);
+
+ gotOptions.headers ??= {};
+ Reflect.deleteProperty(gotOptions.headers, 'Cookie');
+ Reflect.deleteProperty(gotOptions.headers, 'cookie');
+ gotOptions.headers.Cookie = mergedCookie;
+ }
+
+ /**
+ * Function to make the HTTP request. It performs optimizations
+ * on the request such as only downloading the request body if the
+ * received content type matches text/html, application/xml, application/xhtml+xml.
+ */
+ protected async _requestFunction({ request, session, proxyUrl, gotOptions }: RequestFunctionOptions): Promise<IncomingMessage> {
+ const opts = this._getRequestOptions(request, session, proxyUrl, gotOptions);
+
+ try {
+ return await this._requestAsBrowser(opts);
+ } catch (e) {
+ if (e instanceof TimeoutError) {
+ this._handleRequestTimeout(session);
+ return undefined as unknown as IncomingMessage;
+ }
+
+ throw e;
+ }
+ }
+
+ /**
+ * Encodes and parses response according to the provided content type
+ */
+ protected async _parseResponse(request: Request, responseStream: IncomingMessage, crawlingContext: Context) {
+ const { statusCode } = responseStream;
+ const { type, charset } = parseContentTypeFromResponse(responseStream);
+ const { response, encoding } = this._encodeResponse(request, responseStream, charset);
+ const contentType = { type, encoding };
+
+ if (statusCode! >= 500) {
+ const body = await readStreamToString(response, encoding);
+
+ // Errors are often sent as JSON, so attempt to parse them,
+ // despite Accept header being set to text/html.
+ if (type === APPLICATION_JSON_MIME_TYPE) {
+ const errorResponse = JSON.parse(body);
+ let { message } = errorResponse;
+ if (!message) message = util.inspect(errorResponse, { depth: 1, maxArrayLength: 10 });
+ throw new Error(`${statusCode} - ${message}`);
+ }
+
+ // It's not a JSON, so it's probably some text. Get the first 100 chars of it.
+ throw new Error(`${statusCode} - Internal Server Error: ${body.slice(0, 100)}`);
+ } else if (HTML_AND_XML_MIME_TYPES.includes(type)) {
+ const isXml = type.includes('xml');
+ const parsed = await this._parseHTML(response, isXml, crawlingContext);
+ return { ...parsed, isXml, response, contentType };
+ } else {
+ const body = await concatStreamToBuffer(response);
+ return { body, response, contentType };
+ }
+ }
+
+ protected async _parseHTML(response: IncomingMessage, _isXml: boolean, _crawlingContext: Context): Promise<Partial<Context>> {
+ return {
+ body: await concatStreamToBuffer(response),
+ } as Partial<Context>;
+ }
+
+ /**
+ * Combines the provided `requestOptions` with mandatory (non-overridable) values.
+ */
+ protected _getRequestOptions(request: Request, session?: Session, proxyUrl?: string, gotOptions?: OptionsInit) {
+ const requestOptions: OptionsInit & { isStream: true } = {
+ url: request.url,
+ method: request.method as Method,
+ proxyUrl,
+ timeout: { request: this.navigationTimeoutMillis },
+ sessionToken: session,
+ ...gotOptions,
+ headers: { ...request.headers, ...gotOptions?.headers },
+ https: {
+ ...gotOptions?.https,
+ rejectUnauthorized: !this.ignoreSslErrors,
+ },
+ isStream: true,
+ };
+
+ // Delete any possible lowercased header for cookie as they are merged in _applyCookies under the uppercase Cookie header
+ Reflect.deleteProperty(requestOptions.headers!, 'cookie');
+
+ // TODO this is incorrect, the check for man in the middle needs to be done
+ // on individual proxy level, not on the `proxyConfiguration` level,
+ // because users can use normal + MITM proxies in a single configuration.
+ // Disable SSL verification for MITM proxies
+ if (this.proxyConfiguration && this.proxyConfiguration.isManInTheMiddle) {
+ requestOptions.https = {
+ ...requestOptions.https,
+ rejectUnauthorized: false,
+ };
+ }
+
+ if (/PATCH|POST|PUT/.test(request.method)) requestOptions.body = request.payload;
+
+ return requestOptions;
+ }
+
+ protected _encodeResponse(request: Request, response: IncomingMessage, encoding: BufferEncoding): {
+ encoding: BufferEncoding;
+ response: IncomingMessage;
+ } {
+ if (this.forceResponseEncoding) {
+ encoding = this.forceResponseEncoding as BufferEncoding;
+ } else if (!encoding && this.suggestResponseEncoding) {
+ encoding = this.suggestResponseEncoding as BufferEncoding;
+ }
+
+ // Fall back to utf-8 if we still don't have encoding.
+ const utf8 = 'utf8';
+ if (!encoding) return { response, encoding: utf8 };
+
+ // This means that the encoding is one of Node.js supported
+ // encodings and we don't need to re-encode it.
+ if (Buffer.isEncoding(encoding)) return { response, encoding };
+
+ // Try to re-encode a variety of unsupported encodings to utf-8
+ if (iconv.encodingExists(encoding)) {
+ const encodeStream = iconv.encodeStream(utf8);
+ const decodeStream = iconv.decodeStream(encoding).on('error', (err) => encodeStream.emit('error', err));
+ response.on('error', (err: Error) => decodeStream.emit('error', err));
+ const encodedResponse = response.pipe(decodeStream).pipe(encodeStream) as NodeJS.ReadWriteStream & {
+ statusCode?: number;
+ headers: IncomingHttpHeaders;
+ url?: string;
+ };
+ encodedResponse.statusCode = response.statusCode;
+ encodedResponse.headers = response.headers;
+ encodedResponse.url = response.url;
+ return {
+ response: encodedResponse as any,
+ encoding: utf8,
+ };
+ }
+
+ throw new Error(`Resource ${request.url} served with unsupported charset/encoding: ${encoding}`);
+ }
+
+ /**
+ * Checks and extends supported mime types
+ */
+ protected _extendSupportedMimeTypes(additionalMimeTypes: (string | RequestLike | ResponseLike)[]) {
+ for (const mimeType of additionalMimeTypes) {
+ if (mimeType === '*/*') {
+ this.supportedMimeTypes.add(mimeType);
+ continue;
+ }
+
+ try {
+ const parsedType = contentTypeParser.parse(mimeType);
+ this.supportedMimeTypes.add(parsedType.type);
+ } catch (err) {
+ throw new Error(`Can not parse mime type ${mimeType} from "options.additionalMimeTypes".`);
+ }
+ }
+ }
+
+ /**
+ * Handles timeout request
+ */
+ protected _handleRequestTimeout(session?: Session) {
+ session?.markBad();
+ throw new Error(`request timed out after ${this.requestHandlerTimeoutMillis / 1000} seconds.`);
+ }
+
+ private _abortDownloadOfBody(request: Request, response: IncomingMessage) {
+ const { statusCode } = response;
+ const { type } = parseContentTypeFromResponse(response);
+
+ if (statusCode === 406) {
+ request.noRetry = true;
+ throw new Error(`Resource ${request.url} is not available in the format requested by the Accept header. Skipping resource.`);
+ }
+
+ if (!this.supportedMimeTypes.has(type) && !this.supportedMimeTypes.has('*/*') && statusCode! < 500) {
+ request.noRetry = true;
+ throw new Error(`Resource ${request.url} served Content-Type ${type}, `
+ + `but only ${Array.from(this.supportedMimeTypes).join(', ')} are allowed. Skipping resource.`);
+ }
+ }
+
+ /**
+ * @internal wraps public utility for mocking purposes
+ */
+ private _requestAsBrowser = (options: OptionsInit & { isStream: true }) => {
+ return new Promise<IncomingMessage>((resolve, reject) => {
+ const stream = gotScraping(options);
+
+ stream.on('error', reject);
+ stream.on('response', () => {
+ resolve(addResponsePropertiesToStream(stream));
+ });
+ });
+ };
+}
+
+interface RequestFunctionOptions {
+ request: Request;
+ session?: Session;
+ proxyUrl?: string;
+ gotOptions: OptionsInit;
+}
+
+/**
+ * The stream object returned from got does not have the below properties.
+ * At the same time, you can't read data directly from the response stream,
+ * because they won't get emitted unless you also read from the primary
+ * got stream. To be able to work with only one stream, we move the expected props
+ * from the response stream to the got stream.
+ * @internal
+ */
+function addResponsePropertiesToStream(stream: GotRequest) {
+ const properties = [
+ 'statusCode', 'statusMessage', 'headers',
+ 'complete', 'httpVersion', 'rawHeaders',
+ 'rawTrailers', 'trailers', 'url',
+ 'request',
+ ];
+
+ const response = stream.response!;
+
+ response.on('end', () => {
+ // @ts-expect-error
+ Object.assign(stream.rawTrailers, response.rawTrailers);
+ // @ts-expect-error
+ Object.assign(stream.trailers, response.trailers);
+
+ // @ts-expect-error
+ stream.complete = response.complete;
+ });
+
+ for (const prop of properties) {
+ if (!(prop in stream)) {
+ // @ts-expect-error
+ stream[prop] = response[prop as keyof IncomingMessage];
+ }
+ }
+
+ return stream as unknown as IncomingMessage;
+}
+
+/**
+ * Gets parsed content type from response object
+ * @param response HTTP response object
+ */
+function parseContentTypeFromResponse(response: IncomingMessage): { type: string; charset: BufferEncoding } {
+ ow(response, ow.object.partialShape({
+ url: ow.string.url,
+ headers: ow.object,
+ }));
+
+ const { url, headers } = response;
+ let parsedContentType;
+
+ if (headers['content-type']) {
+ try {
+ parsedContentType = contentTypeParser.parse(headers['content-type']);
+ } catch {
+ // Can not parse content type from Content-Type header. Try to parse it from file extension.
+ }
+ }
+
+ // Parse content type from file extension as fallback
+ if (!parsedContentType) {
+ const parsedUrl = new URL(url);
+ const contentTypeFromExtname = mime.contentType(extname(parsedUrl.pathname))
+ || 'application/octet-stream; charset=utf-8'; // Fallback content type, specified in https://tools.ietf.org/html/rfc7231#section-3.1.1.5
+ parsedContentType = contentTypeParser.parse(contentTypeFromExtname);
+ }
+
+ return {
+ type: parsedContentType.type,
+ charset: parsedContentType.parameters.charset as BufferEncoding,
+ };
+}
+
+/**
+ * Creates new {@apilink Router} instance that works based on request labels.
+ * This instance can then serve as a `requestHandler` of your {@apilink HttpCrawler}.
+ * Defaults to the {@apilink HttpCrawlingContext}.
+ *
+ * > Serves as a shortcut for using `Router.create<HttpCrawlingContext>()`.
+ *
+ * ```ts
+ * import { HttpCrawler, createHttpRouter } from 'crawlee';
+ *
+ * const router = createHttpRouter();
+ * router.addHandler('label-a', async (ctx) => {
+ * ctx.log.info('...');
+ * });
+ * router.addDefaultHandler(async (ctx) => {
+ * ctx.log.info('...');
+ * });
+ *
+ * const crawler = new HttpCrawler({
+ * requestHandler: router,
+ * });
+ * await crawler.run();
+ * ```
+ */
+export function createHttpRouter<Context extends HttpCrawlingContext = HttpCrawlingContext>() {
+ return Router.create<Context>();
+}
diff --git a/packages/http-crawler/tsconfig.build.json b/packages/http-crawler/tsconfig.build.json
new file mode 100644
index 000000000..856db0f21
--- /dev/null
+++ b/packages/http-crawler/tsconfig.build.json
@@ -0,0 +1,7 @@
+{
+ "extends": "../../tsconfig.build.json",
+ "compilerOptions": {
+ "outDir": "./dist"
+ },
+ "include": ["src/**/*"]
+}
diff --git a/packages/http-crawler/tsconfig.json b/packages/http-crawler/tsconfig.json
new file mode 100644
index 000000000..52d43eaaa
--- /dev/null
+++ b/packages/http-crawler/tsconfig.json
@@ -0,0 +1,4 @@
+{
+ "extends": "../../tsconfig.json",
+ "include": ["src/**/*"]
+}
diff --git a/packages/utils/package.json b/packages/utils/package.json
index acfc95f6b..5b4a93e27 100644
--- a/packages/utils/package.json
+++ b/packages/utils/package.json
@@ -51,10 +51,7 @@
"@apify/ps-tree": "^1.1.4",
"@crawlee/types": "^3.0.3",
"cheerio": "1.0.0-rc.12",
- "content-type": "^1.0.4",
"got-scraping": "^3.2.9",
- "mime-types": "^2.1.35",
- "ow": "^0.28.1",
"tslib": "^2.4.0"
}
}
diff --git a/packages/utils/src/internals/general.ts b/packages/utils/src/internals/general.ts
index 5d2a43ce7..7324364c8 100644
--- a/packages/utils/src/internals/general.ts
+++ b/packages/utils/src/internals/general.ts
@@ -1,11 +1,5 @@
-import contentTypeParser from 'content-type';
-import mime from 'mime-types';
import fs from 'node:fs/promises';
-import type { IncomingMessage } from 'node:http';
-import path from 'node:path';
import { setTimeout } from 'node:timers/promises';
-import { URL } from 'node:url';
-import ow from 'ow';
/**
* Default regular expression to match URLs in a string that may be plain text, JSON, CSV or other. It supports common URL characters
@@ -95,39 +89,3 @@ export function snakeCaseToCamelCase(snakeCaseStr: string): string {
})
.join('');
}
-
-/**
- * Gets parsed content type from response object
- * @param response HTTP response object
- * @ignore
- */
-export function parseContentTypeFromResponse(response: IncomingMessage): { type: string; charset: BufferEncoding } {
- ow(response, ow.object.partialShape({
- url: ow.string.url,
- headers: ow.object,
- }));
-
- const { url, headers } = response;
- let parsedContentType;
-
- if (headers['content-type']) {
- try {
- parsedContentType = contentTypeParser.parse(headers['content-type']);
- } catch {
- // Can not parse content type from Content-Type header. Try to parse it from file extension.
- }
- }
-
- // Parse content type from file extension as fallback
- if (!parsedContentType) {
- const parsedUrl = new URL(url);
- const contentTypeFromExtname = mime.contentType(path.extname(parsedUrl.pathname))
- || 'application/octet-stream; charset=utf-8'; // Fallback content type, specified in https://tools.ietf.org/html/rfc7231#section-3.1.1.5
- parsedContentType = contentTypeParser.parse(contentTypeFromExtname);
- }
-
- return {
- type: parsedContentType.type,
- charset: parsedContentType.parameters.charset as BufferEncoding,
- };
-}
diff --git a/test/core/crawlers/basic_crawler.test.ts b/test/core/crawlers/basic_crawler.test.ts
index d48cc106a..7a59026ad 100644
--- a/test/core/crawlers/basic_crawler.test.ts
+++ b/test/core/crawlers/basic_crawler.test.ts
@@ -55,6 +55,9 @@ describe('BasicCrawler', () => {
afterAll(async () => {
await localStorageEmulator.destroy();
+ });
+
+ afterAll(async () => {
log.setLevel(logLevel);
});
diff --git a/test/core/crawlers/browser_crawler.test.ts b/test/core/crawlers/browser_crawler.test.ts
index 7b140cb9d..bcfd4998b 100644
--- a/test/core/crawlers/browser_crawler.test.ts
+++ b/test/core/crawlers/browser_crawler.test.ts
@@ -55,14 +55,17 @@ describe('BrowserCrawler', () => {
puppeteerPlugin = new PuppeteerPlugin(puppeteer);
});
- afterEach(() => {
+ afterEach(async () => {
puppeteerPlugin = null;
});
+ afterAll(async () => {
+ await localStorageEmulator.destroy();
+ });
+
afterAll(async () => {
log.setLevel(logLevel);
process.env.CRAWLEE_HEADLESS = prevEnvHeadless;
- await localStorageEmulator.destroy();
});
test('should work', async () => {
diff --git a/test/core/crawlers/cheerio_crawler.test.ts b/test/core/crawlers/cheerio_crawler.test.ts
index 51803eeb9..3d923c8f5 100644
--- a/test/core/crawlers/cheerio_crawler.test.ts
+++ b/test/core/crawlers/cheerio_crawler.test.ts
@@ -197,8 +197,11 @@ describe('CheerioCrawler', () => {
});
afterAll(async () => {
- log.setLevel(logLevel);
await localStorageEmulator.destroy();
+ });
+
+ afterAll(async () => {
+ log.setLevel(logLevel);
server.close();
});
diff --git a/test/core/crawlers/http_crawler.test.ts b/test/core/crawlers/http_crawler.test.ts
new file mode 100644
index 000000000..2fed6b46c
--- /dev/null
+++ b/test/core/crawlers/http_crawler.test.ts
@@ -0,0 +1,153 @@
+import { HttpCrawler } from '@crawlee/http';
+import type { AddressInfo } from 'node:net';
+import http from 'node:http';
+import { MemoryStorageEmulator } from 'test/shared/MemoryStorageEmulator';
+
+const router = new Map<string, http.RequestListener>();
+router.set('/', (req, res) => {
+ res.setHeader('content-type', 'text/html; charset=utf-8');
+ res.end(`<html><head><title>Example Domain</title></head></html>`);
+});
+
+router.set('/hello.html', (req, res) => {
+ res.end(`<html><head><title>Example Domain</title></head></html>`);
+});
+
+router.set('/noext', (req, res) => {
+ res.end(`<html><head><title>Example Domain</title></head></html>`);
+});
+
+router.set('/invalidContentType', (req, res) => {
+ res.setHeader('content-type', 'crazy-stuff; charset=utf-8');
+ res.end(`<html><head><title>Example Domain</title></head></html>`);
+});
+
+let server: http.Server;
+let url: string;
+
+beforeAll((cb) => {
+ server = http.createServer((request, response) => {
+ try {
+ const requestUrl = new URL(request.url, 'http://localhost');
+ router.get(requestUrl.pathname)(request, response);
+ } catch (error) {
+ response.destroy();
+ }
+ });
+
+ server.listen(() => {
+ url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+ cb();
+ });
+});
+
+afterAll((cb) => {
+ server.close(cb);
+});
+
+const localStorageEmulator = new MemoryStorageEmulator();
+
+beforeEach(async () => {
+ await localStorageEmulator.init();
+});
+
+afterAll(async () => {
+ await localStorageEmulator.destroy();
+});
+
+test('works', async () => {
+ const results: string[] = [];
+
+ const crawler = new HttpCrawler({
+ maxRequestRetries: 0,
+ requestHandler: ({ body }) => {
+ results.push(body as string);
+ },
+ });
+
+ await crawler.run([url]);
+
+ expect(results[0].includes('Example Domain')).toBeTruthy();
+});
+
+test('should parse content type from header', async () => {
+ const results: { type: string; encoding: BufferEncoding }[] = [];
+
+ const crawler = new HttpCrawler({
+ maxRequestRetries: 0,
+ requestHandler: ({ contentType }) => {
+ results.push(contentType);
+ },
+ });
+
+ await crawler.run([url]);
+
+ expect(results).toStrictEqual([
+ {
+ type: 'text/html',
+ encoding: 'utf-8',
+ },
+ ]);
+});
+
+test('should parse content type from file extension', async () => {
+ const results: { type: string; encoding: BufferEncoding }[] = [];
+
+ const crawler = new HttpCrawler({
+ maxRequestRetries: 0,
+ requestHandler: ({ contentType }) => {
+ results.push(contentType);
+ },
+ });
+
+ await crawler.run([`${url}/hello.html`]);
+
+ expect(results).toStrictEqual([
+ {
+ type: 'text/html',
+ encoding: 'utf-8',
+ },
+ ]);
+});
+
+test('no content type defaults to octet-stream', async () => {
+ const results: { type: string; encoding: BufferEncoding }[] = [];
+
+ const crawler = new HttpCrawler({
+ maxRequestRetries: 0,
+ additionalMimeTypes: ['*/*'],
+ requestHandler: ({ contentType }) => {
+ results.push(contentType);
+ },
+ });
+
+ await crawler.run([`${url}/noext`]);
+
+ expect(results).toStrictEqual([
+ {
+ type: 'application/octet-stream',
+ encoding: 'utf-8',
+ },
+ ]);
+});
+
+test('invalid content type defaults to octet-stream', async () => {
+ const results: { type: string; encoding: BufferEncoding }[] = [];
+
+ const crawler = new HttpCrawler({
+ maxRequestRetries: 0,
+ additionalMimeTypes: ['*/*'],
+ requestHandler: ({ contentType }) => {
+ results.push(contentType);
+ },
+ });
+
+ await crawler.run([`${url}/invalidContentType`]);
+
+ expect(results).toStrictEqual([
+ {
+ type: 'application/octet-stream',
+ encoding: 'utf-8',
+ },
+ ]);
+});
diff --git a/test/core/crawlers/playwright_crawler.test.ts b/test/core/crawlers/playwright_crawler.test.ts
index ed0e9f43f..8e2efc754 100644
--- a/test/core/crawlers/playwright_crawler.test.ts
+++ b/test/core/crawlers/playwright_crawler.test.ts
@@ -52,10 +52,13 @@ describe('PlaywrightCrawler', () => {
requestList = await RequestList.open(`sources-${Math.random() * 10000}`, sources);
});
+ afterAll(async () => {
+ await localStorageEmulator.destroy();
+ });
+
afterAll(async () => {
log.setLevel(logLevel);
process.env.CRAWLEE_HEADLESS = prevEnvHeadless;
- await localStorageEmulator.destroy();
});
afterAll(async () => {
server.close();
diff --git a/test/core/crawlers/puppeteer_crawler.test.ts b/test/core/crawlers/puppeteer_crawler.test.ts
index 978b452aa..aa719f940 100644
--- a/test/core/crawlers/puppeteer_crawler.test.ts
+++ b/test/core/crawlers/puppeteer_crawler.test.ts
@@ -73,10 +73,13 @@ describe('PuppeteerCrawler', () => {
requestList = await RequestList.open(`sources-${Math.random() * 10000}`, sources);
});
+ afterAll(async () => {
+ await localStorageEmulator.destroy();
+ });
+
afterAll(async () => {
log.setLevel(logLevel);
process.env.CRAWLEE_HEADLESS = prevEnvHeadless;
- await localStorageEmulator.destroy();
await Promise.all(servers.map((server) => promisify(server.close.bind(server))(true)));
await promisify(target.close.bind(target))();
diff --git a/test/e2e/cheerio-default-ts/actor/package.json b/test/e2e/cheerio-default-ts/actor/package.json
index 406eecb77..9bf8d15a4 100644
--- a/test/e2e/cheerio-default-ts/actor/package.json
+++ b/test/e2e/cheerio-default-ts/actor/package.json
@@ -7,6 +7,7 @@
"@apify/storage-local": "^2.1.0",
"@crawlee/basic": "file:./packages/basic-crawler",
"@crawlee/browser-pool": "file:./packages/browser-pool",
+ "@crawlee/http": "file:./packages/http-crawler",
"@crawlee/cheerio": "file:./packages/cheerio-crawler",
"@crawlee/core": "file:./packages/core",
"@crawlee/memory-storage": "file:./packages/memory-storage",
diff --git a/test/e2e/cheerio-default/actor/package.json b/test/e2e/cheerio-default/actor/package.json
index 6b9a8426e..dd796e9a2 100644
--- a/test/e2e/cheerio-default/actor/package.json
+++ b/test/e2e/cheerio-default/actor/package.json
@@ -7,6 +7,7 @@
"@apify/storage-local": "^2.1.0",
"@crawlee/basic": "file:./packages/basic-crawler",
"@crawlee/browser-pool": "file:./packages/browser-pool",
+ "@crawlee/http": "file:./packages/http-crawler",
"@crawlee/cheerio": "file:./packages/cheerio-crawler",
"@crawlee/core": "file:./packages/core",
"@crawlee/memory-storage": "file:./packages/memory-storage",
diff --git a/test/e2e/cheerio-enqueue-links/actor/package.json b/test/e2e/cheerio-enqueue-links/actor/package.json
index 869503d8e..223fda623 100644
--- a/test/e2e/cheerio-enqueue-links/actor/package.json
+++ b/test/e2e/cheerio-enqueue-links/actor/package.json
@@ -7,6 +7,7 @@
"@apify/storage-local": "^2.1.0",
"@crawlee/basic": "file:./packages/basic-crawler",
"@crawlee/browser-pool": "file:./packages/browser-pool",
+ "@crawlee/http": "file:./packages/http-crawler",
"@crawlee/cheerio": "file:./packages/cheerio-crawler",
"@crawlee/core": "file:./packages/core",
"@crawlee/memory-storage": "file:./packages/memory-storage",
diff --git a/test/e2e/cheerio-ignore-ssl-errors/actor/package.json b/test/e2e/cheerio-ignore-ssl-errors/actor/package.json
index 134b9be7b..d70316829 100644
--- a/test/e2e/cheerio-ignore-ssl-errors/actor/package.json
+++ b/test/e2e/cheerio-ignore-ssl-errors/actor/package.json
@@ -7,6 +7,7 @@
"@apify/storage-local": "^2.1.0",
"@crawlee/basic": "file:./packages/basic-crawler",
"@crawlee/browser-pool": "file:./packages/browser-pool",
+ "@crawlee/http": "file:./packages/http-crawler",
"@crawlee/cheerio": "file:./packages/cheerio-crawler",
"@crawlee/core": "file:./packages/core",
"@crawlee/memory-storage": "file:./packages/memory-storage",
diff --git a/test/e2e/cheerio-initial-cookies/actor/package.json b/test/e2e/cheerio-initial-cookies/actor/package.json
index 8494d008d..2698fd088 100644
--- a/test/e2e/cheerio-initial-cookies/actor/package.json
+++ b/test/e2e/cheerio-initial-cookies/actor/package.json
@@ -7,6 +7,7 @@
"@apify/storage-local": "^2.1.0",
"@crawlee/basic": "file:./packages/basic-crawler",
"@crawlee/browser-pool": "file:./packages/browser-pool",
+ "@crawlee/http": "file:./packages/http-crawler",
"@crawlee/cheerio": "file:./packages/cheerio-crawler",
"@crawlee/core": "file:./packages/core",
"@crawlee/memory-storage": "file:./packages/memory-storage",
diff --git a/test/e2e/cheerio-max-requests/actor/package.json b/test/e2e/cheerio-max-requests/actor/package.json
index 03714234c..454a0877e 100644
--- a/test/e2e/cheerio-max-requests/actor/package.json
+++ b/test/e2e/cheerio-max-requests/actor/package.json
@@ -7,6 +7,7 @@
"@apify/storage-local": "^2.1.0",
"@crawlee/basic": "file:./packages/basic-crawler",
"@crawlee/browser-pool": "file:./packages/browser-pool",
+ "@crawlee/http": "file:./packages/http-crawler",
"@crawlee/cheerio": "file:./packages/cheerio-crawler",
"@crawlee/core": "file:./packages/core",
"@crawlee/memory-storage": "file:./packages/memory-storage",
diff --git a/test/e2e/cheerio-page-info/actor/package.json b/test/e2e/cheerio-page-info/actor/package.json
index df233c2ea..72afad441 100644
--- a/test/e2e/cheerio-page-info/actor/package.json
+++ b/test/e2e/cheerio-page-info/actor/package.json
@@ -7,6 +7,7 @@
"@apify/storage-local": "^2.1.0",
"@crawlee/basic": "file:./packages/basic-crawler",
"@crawlee/browser-pool": "file:./packages/browser-pool",
+ "@crawlee/http": "file:./packages/http-crawler",
"@crawlee/cheerio": "file:./packages/cheerio-crawler",
"@crawlee/core": "file:./packages/core",
"@crawlee/memory-storage": "file:./packages/memory-storage",
diff --git a/test/e2e/cheerio-throw-on-ssl-errors/actor/package.json b/test/e2e/cheerio-throw-on-ssl-errors/actor/package.json
index 06cfb6153..e6014be1a 100644
--- a/test/e2e/cheerio-throw-on-ssl-errors/actor/package.json
+++ b/test/e2e/cheerio-throw-on-ssl-errors/actor/package.json
@@ -7,6 +7,7 @@
"@apify/storage-local": "^2.1.0",
"@crawlee/basic": "file:./packages/basic-crawler",
"@crawlee/browser-pool": "file:./packages/browser-pool",
+ "@crawlee/http": "file:./packages/http-crawler",
"@crawlee/cheerio": "file:./packages/cheerio-crawler",
"@crawlee/core": "file:./packages/core",
"@crawlee/memory-storage": "file:./packages/memory-storage",
diff --git a/test/e2e/request-queue-zero-concurrency/actor/package.json b/test/e2e/request-queue-zero-concurrency/actor/package.json
index 8e24d9425..643244c75 100644
--- a/test/e2e/request-queue-zero-concurrency/actor/package.json
+++ b/test/e2e/request-queue-zero-concurrency/actor/package.json
@@ -7,6 +7,7 @@
"@apify/storage-local": "^2.1.0",
"@crawlee/basic": "file:./packages/basic-crawler",
"@crawlee/browser-pool": "file:./packages/browser-pool",
+ "@crawlee/http": "file:./packages/http-crawler",
"@crawlee/cheerio": "file:./packages/cheerio-crawler",
"@crawlee/core": "file:./packages/core",
"@crawlee/memory-storage": "file:./packages/memory-storage",
diff --git a/test/e2e/request-skip-navigation/actor/package.json b/test/e2e/request-skip-navigation/actor/package.json
index 92f944d85..38fe57048 100644
--- a/test/e2e/request-skip-navigation/actor/package.json
+++ b/test/e2e/request-skip-navigation/actor/package.json
@@ -7,6 +7,7 @@
"@apify/storage-local": "^2.1.0",
"@crawlee/basic": "file:./packages/basic-crawler",
"@crawlee/browser-pool": "file:./packages/browser-pool",
+ "@crawlee/http": "file:./packages/http-crawler",
"@crawlee/cheerio": "file:./packages/cheerio-crawler",
"@crawlee/core": "file:./packages/core",
"@crawlee/memory-storage": "file:./packages/memory-storage",
diff --git a/test/utils/general.test.ts b/test/utils/general.test.ts
index eaa8c74e6..01b9d436e 100644
--- a/test/utils/general.test.ts
+++ b/test/utils/general.test.ts
@@ -1,4 +1,4 @@
-import { isDocker, weightedAvg, sleep, snakeCaseToCamelCase, parseContentTypeFromResponse } from '@crawlee/utils';
+import { isDocker, weightedAvg, sleep, snakeCaseToCamelCase } from '@crawlee/utils';
import type { IncomingMessage } from 'node:http';
import asyncFs from 'node:fs/promises';
@@ -90,38 +90,3 @@ describe('snakeCaseToCamelCase()', () => {
});
});
});
-
-describe('parseContentTypeFromResponse', () => {
- test('should parse content type from header', () => {
- const parsed = parseContentTypeFromResponse({ url: 'http://example.com', headers: { 'content-type': 'text/html; charset=utf-8' } } as IncomingMessage);
- expect(parsed.type).toBe('text/html');
- expect(parsed.charset).toBe('utf-8');
- });
-
- test('should parse content type from file extension', () => {
- const parsedHtml = parseContentTypeFromResponse({ url: 'http://www.example.com/foo/file.html?someparam=foo', headers: {} } as IncomingMessage);
- expect(parsedHtml.type).toBe('text/html');
- expect(parsedHtml.charset).toBe('utf-8');
-
- const parsedTxt = parseContentTypeFromResponse({ url: 'http://www.example.com/foo/file.txt', headers: {} } as IncomingMessage);
- expect(parsedTxt.type).toBe('text/plain');
- expect(parsedTxt.charset).toBe('utf-8');
- });
-
- test('should return default content type for bad content type headers', () => {
- const parsedWithoutCt = parseContentTypeFromResponse({ url: 'http://www.example.com/foo/file', headers: {} } as IncomingMessage);
- expect(parsedWithoutCt.type).toBe('application/octet-stream');
- expect(parsedWithoutCt.charset).toBe('utf-8');
-
- const parsedBadHeader = parseContentTypeFromResponse({
- url: 'http://www.example.com/foo/file.html',
- headers: { 'content-type': 'text/html,text/html' },
- } as IncomingMessage);
- expect(parsedBadHeader.type).toBe('text/html');
- expect(parsedBadHeader.charset).toBe('utf-8');
-
- const parsedReallyBad = parseContentTypeFromResponse({ url: 'http://www.example.com/foo', headers: { 'content-type': 'crazy-stuff' } } as IncomingMessage);
- expect(parsedReallyBad.type).toBe('application/octet-stream');
- expect(parsedReallyBad.charset).toBe('utf-8');
- });
-});
diff --git a/tsconfig.json b/tsconfig.json
index 6b4976726..9482010cb 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -6,6 +6,7 @@
"crawlee": ["packages/crawlee/src"],
"@crawlee/basic": ["packages/basic-crawler/src"],
"@crawlee/browser": ["packages/browser-crawler/src"],
+ "@crawlee/http": ["packages/http-crawler/src"],
"@crawlee/cheerio": ["packages/cheerio-crawler/src"],
"@crawlee/playwright": ["packages/playwright-crawler/src"],
"@crawlee/puppeteer": ["packages/puppeteer-crawler/src"],
diff --git a/website/docusaurus.config.js b/website/docusaurus.config.js
index 0a6015563..bd78632e9 100644
--- a/website/docusaurus.config.js
+++ b/website/docusaurus.config.js
@@ -10,6 +10,7 @@ const packages = [
'browser-pool',
'basic-crawler',
'browser-crawler',
+ 'http-crawler',
'cheerio-crawler',
'puppeteer-crawler',
'playwright-crawler',
@@ -23,6 +24,7 @@ const packagesOrder = [
'@crawlee/puppeteer',
'@crawlee/playwright',
'@crawlee/basic',
+ '@crawlee/http',
'@crawlee/browser',
'@crawlee/memory-storage',
'@crawlee/browser-pool',