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.

Feature preview created.

Petr Patek6340eb0665e0
diff --git a/src/cheerio_crawler.js b/src/cheerio_crawler.js
index 68e8ec3b5..d514956c2 100644
--- a/src/cheerio_crawler.js
+++ b/src/cheerio_crawler.js
@@ -29,6 +29,7 @@ const DEFAULT_OPTIONS = {
maxEventLoopOverloadedRatio: 0.7,
},
},
+ beforeRequest: ({ request }) => request,
};
/**
@@ -225,6 +226,7 @@ class CheerioCrawler {
maxRequestsPerCrawl,
handleFailedRequestFunction,
autoscaledPoolOptions,
+ beforeRequest,
} = _.defaults({}, options, DEFAULT_OPTIONS);
checkParamOrThrow(handlePageFunction, 'options.handlePageFunction', 'Function');
@@ -236,6 +238,7 @@ class CheerioCrawler {
checkParamOrThrow(apifyProxyGroups, 'options.apifyProxyGroups', 'Maybe [String]');
checkParamOrThrow(apifyProxySession, 'options.apifyProxySession', 'Maybe String');
checkParamOrThrow(proxyUrls, 'options.proxyUrls', 'Maybe [String]');
+ checkParamOrThrow(handlePageFunction, 'options.beforeRequest', 'Maybe Function');
// Enforce valid proxy configuration
if (proxyUrls && !proxyUrls.length) throw new Error('Parameter "options.proxyUrls" of type Array must not be empty');
if (useApifyProxy && proxyUrls) throw new Error('Cannot combine "options.useApifyProxy" with "options.proxyUrls"!');
@@ -250,6 +253,7 @@ class CheerioCrawler {
this.apifyProxySession = apifyProxySession;
this.proxyUrls = _.shuffle(proxyUrls);
this.lastUsedProxyUrlIndex = 0;
+ this.beforeRequest = beforeRequest;
this.basicCrawler = new BasicCrawler({
// Basic crawler options.
@@ -292,8 +296,9 @@ class CheerioCrawler {
* @ignore
*/
async _handleRequestFunction({ request, autoscaledPool }) {
+ const modifiedRequest = await this.beforeRequest({ request });
const response = await addTimeoutToPromise(
- this._requestFunction({ request }),
+ this._requestFunction({ request: modifiedRequest }),
this.requestTimeoutMillis,
'CheerioCrawler: requestFunction timed out.',
);