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.
TypeScript apifyautomationcrawlercrawlingheadlessheadless-chromejavascriptnodejsnpmplaywrightpuppeteerscraperscrapingtypescriptweb-crawlerweb-crawlingweb-scraping
feat: add `onSkippedRequest` option (#2916)
Martin Adámek764f99203627
diff --git a/packages/basic-crawler/src/internals/basic-crawler.ts b/packages/basic-crawler/src/internals/basic-crawler.tsindex 25b195afb..54c77c173 100644--- a/packages/basic-crawler/src/internals/basic-crawler.ts+++ b/packages/basic-crawler/src/internals/basic-crawler.ts@@ -21,6 +21,7 @@ import type {RouterRoutes,Session,SessionPoolOptions,+ SkippedRequestCallback,Source,StatisticsOptions,StatisticState,@@ -349,6 +350,12 @@ export interface BasicCrawlerOptions<Context extends CrawlingContext = BasicCraw*/respectRobotsTxtFile?: boolean;+ /**+ * When a request is skipped for some reason, you can use this callback to act on it.+ * This is currently fired only for requests skipped based on robots.txt file.+ */+ onSkippedRequest?: SkippedRequestCallback;+/** @internal */log?: Log;@@ -517,6 +524,7 @@ export class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContextprotected httpClient: BaseHttpClient;protected retryOnBlocked: boolean;protected respectRobotsTxtFile: boolean;+ protected onSkippedRequest?: SkippedRequestCallback;private _closeEvents?: boolean;private experiments: CrawlerExperiments;@@ -552,6 +560,7 @@ export class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContextretryOnBlocked: ow.optional.boolean,respectRobotsTxtFile: ow.optional.boolean,+ onSkippedRequest: ow.optional.function,httpClient: ow.optional.object,// AutoscaledPool shorthands@@ -595,6 +604,7 @@ export class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContextretryOnBlocked = false,respectRobotsTxtFile = false,+ onSkippedRequest,// internallog = defaultLog.child({ prefix: this.constructor.name }),@@ -668,6 +678,7 @@ export class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContextthis.retryOnBlocked = retryOnBlocked;this.respectRobotsTxtFile = respectRobotsTxtFile;+ this.onSkippedRequest = onSkippedRequest;this._handlePropertyNameChange({newName: 'requestHandlerTimeoutSecs',@@ -1059,6 +1070,7 @@ export class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContextallowedRequests.push(request);} else {skipped.add(url);+ await this.onSkippedRequest?.({ url, reason: 'robotsTxt' });}}@@ -1066,6 +1078,14 @@ export class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContextthis.log.warning(`Some requests were skipped because they were disallowed based on the robots.txt file`, {skipped: [...skipped],});++ if (this.onSkippedRequest) {+ await Promise.all(+ [...skipped].map((url) => {+ return this.onSkippedRequest!({ url, reason: 'robotsTxt' });+ }),+ );+ }}return requestQueue.addRequestsBatched(allowedRequests, options);@@ -1355,12 +1375,16 @@ export class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContext}if (!(await this.isAllowedBasedOnRobotsTxtFile(request.url))) {- this.log.debug(+ this.log.warning(`Skipping request ${request.url} (${request.id}) because it is disallowed based on robots.txt`,);request.state = RequestState.SKIPPED;request.noRetry = true;await source.markRequestHandled(request);+ await this.onSkippedRequest?.({+ url: request.url,+ reason: 'robotsTxt',+ });return;}@@ -1385,6 +1409,7 @@ export class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContext// specify the RQ first to allow overriding itrequestQueue: await this.getRequestQueue(),robotsTxtFile: await this.getRobotsTxtFileForUrl(request!.url),+ onSkippedRequest: this.onSkippedRequest,...options,});},diff --git a/packages/browser-crawler/src/internals/browser-crawler.ts b/packages/browser-crawler/src/internals/browser-crawler.tsindex 0a1748266..a0eb8ca9f 100644--- a/packages/browser-crawler/src/internals/browser-crawler.ts+++ b/packages/browser-crawler/src/internals/browser-crawler.ts@@ -11,6 +11,7 @@ import type {RequestHandler,RequestProvider,Session,+ SkippedRequestCallback,} from '@crawlee/basic';import {BASIC_CRAWLER_TIMEOUT_BUFFER_SECS,@@ -626,6 +627,7 @@ export abstract class BrowserCrawler<page,requestQueue: await this.getRequestQueue(),robotsTxtFile: await this.getRobotsTxtFileForUrl(crawlingContext.request.url),+ onSkippedRequest: this.onSkippedRequest,originalRequestUrl: crawlingContext.request.url,finalRequestUrl: crawlingContext.request.loadedUrl,});@@ -792,6 +794,7 @@ interface EnqueueLinksInternalOptions {page: CommonPage;requestQueue: RequestProvider;robotsTxtFile?: RobotsTxtFile;+ onSkippedRequest?: SkippedRequestCallback;originalRequestUrl: string;finalRequestUrl?: string;}@@ -802,6 +805,7 @@ export async function browserCrawlerEnqueueLinks({page,requestQueue,robotsTxtFile,+ onSkippedRequest,originalRequestUrl,finalRequestUrl,}: EnqueueLinksInternalOptions) {@@ -821,6 +825,7 @@ export async function browserCrawlerEnqueueLinks({return enqueueLinks({requestQueue,robotsTxtFile,+ onSkippedRequest,urls,baseUrl,...(options as EnqueueLinksOptions),diff --git a/packages/cheerio-crawler/src/internals/cheerio-crawler.ts b/packages/cheerio-crawler/src/internals/cheerio-crawler.tsindex db5259f51..700ef3e0c 100644--- a/packages/cheerio-crawler/src/internals/cheerio-crawler.ts+++ b/packages/cheerio-crawler/src/internals/cheerio-crawler.ts@@ -12,6 +12,7 @@ import type {RequestHandler,RequestProvider,RouterRoutes,+ SkippedRequestCallback,} from '@crawlee/http';import { enqueueLinks, HttpCrawler, resolveBaseUrlForEnqueueLinksFiltering, Router } from '@crawlee/http';import type { Dictionary } from '@crawlee/types';@@ -194,6 +195,7 @@ export class CheerioCrawler extends HttpCrawler<CheerioCrawlingContext> {$,requestQueue: await this.getRequestQueue(),robotsTxtFile: await this.getRobotsTxtFileForUrl(crawlingContext.request.url),+ onSkippedRequest: this.onSkippedRequest,originalRequestUrl: crawlingContext.request.url,finalRequestUrl: crawlingContext.request.loadedUrl,});@@ -240,6 +242,7 @@ interface EnqueueLinksInternalOptions {$: cheerio.CheerioAPI | null;requestQueue: RequestProvider;robotsTxtFile?: RobotsTxtFile;+ onSkippedRequest?: SkippedRequestCallback;originalRequestUrl: string;finalRequestUrl?: string;}@@ -250,6 +253,7 @@ export async function cheerioCrawlerEnqueueLinks({$,requestQueue,robotsTxtFile,+ onSkippedRequest,originalRequestUrl,finalRequestUrl,}: EnqueueLinksInternalOptions) {@@ -273,6 +277,7 @@ export async function cheerioCrawlerEnqueueLinks({return enqueueLinks({requestQueue,robotsTxtFile,+ onSkippedRequest,urls,baseUrl,...options,diff --git a/packages/core/src/enqueue_links/enqueue_links.ts b/packages/core/src/enqueue_links/enqueue_links.tsindex 8b3a9042c..2e9d73e09 100644--- a/packages/core/src/enqueue_links/enqueue_links.ts+++ b/packages/core/src/enqueue_links/enqueue_links.ts@@ -1,4 +1,4 @@-import type { BatchAddRequestsResult, Dictionary } from '@crawlee/types';+import type { Awaitable, BatchAddRequestsResult, Dictionary } from '@crawlee/types';import { type RobotsTxtFile } from '@crawlee/utils';import ow from 'ow';import { getDomain } from 'tldts';@@ -18,6 +18,8 @@ import {filterRequestsByPatterns,} from './shared';+export type SkippedRequestCallback = (args: { url: string; reason: 'robotsTxt' }) => Awaitable<void>;+export interface EnqueueLinksOptions extends RequestQueueOperationOptions {/** Limit the amount of actually enqueued URLs to this number. Useful for testing across the entire crawling scope. */limit?: number;@@ -165,6 +167,12 @@ export interface EnqueueLinksOptions extends RequestQueueOperationOptions {* If provided, disallowed URLs will be ignored.*/robotsTxtFile?: RobotsTxtFile;++ /**+ * When a request is skipped for some reason, you can use this callback to act on it.+ * This is currently fired only for requests skipped based on robots.txt file.+ */+ onSkippedRequest?: SkippedRequestCallback;}/**@@ -264,6 +272,7 @@ export async function enqueueLinks(urls: ow.array.ofType(ow.string),requestQueue: ow.object.hasKeys('fetchNextRequest', 'addRequest'),robotsTxtFile: ow.optional.object.hasKeys('isAllowed'),+ onSkippedRequest: ow.optional.function,forefront: ow.optional.boolean,skipNavigation: ow.optional.boolean,limit: ow.optional.number,@@ -295,6 +304,7 @@ export async function enqueueLinks(forefront,waitForAllRequestsToBeAdded,robotsTxtFile,+ onSkippedRequest,} = options;const urlExcludePatternObjects: UrlPatternObject[] = [];@@ -373,9 +383,24 @@ export async function enqueueLinks(let requestOptions = createRequestOptions(urls, options);if (robotsTxtFile) {+ const skippedRequests: RequestOptions[] = [];+requestOptions = requestOptions.filter((request) => {- return robotsTxtFile.isAllowed(request.url);+ if (robotsTxtFile.isAllowed(request.url)) {+ return true;+ }++ skippedRequests.push(request);+ return false;});++ if (onSkippedRequest && skippedRequests.length > 0) {+ await Promise.all(+ skippedRequests.map((request) => {+ return onSkippedRequest({ url: request.url, reason: 'robotsTxt' });+ }),+ );+ }}if (transformRequestFunction) {diff --git a/packages/jsdom-crawler/src/internals/jsdom-crawler.ts b/packages/jsdom-crawler/src/internals/jsdom-crawler.tsindex 584729a5c..5e0dde069 100644--- a/packages/jsdom-crawler/src/internals/jsdom-crawler.ts+++ b/packages/jsdom-crawler/src/internals/jsdom-crawler.ts@@ -11,6 +11,7 @@ import type {RequestHandler,RequestProvider,RouterRoutes,+ SkippedRequestCallback,} from '@crawlee/http';import {enqueueLinks,@@ -305,6 +306,7 @@ export class JSDOMCrawler extends HttpCrawler<JSDOMCrawlingContext> {window,requestQueue: await this.getRequestQueue(),robotsTxtFile: await this.getRobotsTxtFileForUrl(crawlingContext.request.url),+ onSkippedRequest: this.onSkippedRequest,originalRequestUrl: crawlingContext.request.url,finalRequestUrl: crawlingContext.request.loadedUrl,});@@ -345,6 +347,7 @@ interface EnqueueLinksInternalOptions {window: DOMWindow | null;requestQueue: RequestProvider;robotsTxtFile?: RobotsTxtFile;+ onSkippedRequest?: SkippedRequestCallback;originalRequestUrl: string;finalRequestUrl?: string;}@@ -355,6 +358,7 @@ export async function domCrawlerEnqueueLinks({window,requestQueue,robotsTxtFile,+ onSkippedRequest,originalRequestUrl,finalRequestUrl,}: EnqueueLinksInternalOptions) {@@ -378,6 +382,7 @@ export async function domCrawlerEnqueueLinks({return enqueueLinks({requestQueue,robotsTxtFile,+ onSkippedRequest,urls,baseUrl,...options,diff --git a/packages/linkedom-crawler/src/internals/linkedom-crawler.ts b/packages/linkedom-crawler/src/internals/linkedom-crawler.tsindex 7228979a2..39153c263 100644--- a/packages/linkedom-crawler/src/internals/linkedom-crawler.ts+++ b/packages/linkedom-crawler/src/internals/linkedom-crawler.ts@@ -10,6 +10,7 @@ import type {RequestHandler,RequestProvider,RouterRoutes,+ SkippedRequestCallback,} from '@crawlee/http';import {enqueueLinks,@@ -188,6 +189,7 @@ export class LinkeDOMCrawler extends HttpCrawler<LinkeDOMCrawlingContext> {window: document.defaultView,requestQueue: await this.getRequestQueue(),robotsTxtFile: await this.getRobotsTxtFileForUrl(crawlingContext.request.url),+ onSkippedRequest: this.onSkippedRequest,originalRequestUrl: crawlingContext.request.url,finalRequestUrl: crawlingContext.request.loadedUrl,});@@ -228,6 +230,7 @@ interface EnqueueLinksInternalOptions {window: Window | null;requestQueue: RequestProvider;robotsTxtFile?: RobotsTxtFile;+ onSkippedRequest?: SkippedRequestCallback;originalRequestUrl: string;finalRequestUrl?: string;}@@ -238,6 +241,7 @@ export async function linkedomCrawlerEnqueueLinks({window,requestQueue,robotsTxtFile,+ onSkippedRequest,originalRequestUrl,finalRequestUrl,}: EnqueueLinksInternalOptions) {@@ -261,6 +265,7 @@ export async function linkedomCrawlerEnqueueLinks({return enqueueLinks({requestQueue,robotsTxtFile,+ onSkippedRequest,urls,baseUrl,...options,diff --git a/test/e2e/adaptive-playwright-robots-file/actor/.actor/actor.json b/test/e2e/adaptive-playwright-robots-file/actor/.actor/actor.jsonnew file mode 100644index 000000000..207116600--- /dev/null+++ b/test/e2e/adaptive-playwright-robots-file/actor/.actor/actor.json@@ -0,0 +1,7 @@+{+ "actorSpecification": 1,+ "name": "test-adaptive-playwright-robots-file",+ "version": "0.0",+ "buildTag": "latest",+ "env": null+}diff --git a/test/e2e/adaptive-playwright-robots-file/actor/.gitignore b/test/e2e/adaptive-playwright-robots-file/actor/.gitignorenew file mode 100644index 000000000..ced7cbfc5--- /dev/null+++ b/test/e2e/adaptive-playwright-robots-file/actor/.gitignore@@ -0,0 +1,7 @@+.idea+.DS_Store+node_modules+package-lock.json+apify_storage+crawlee_storage+storagediff --git a/test/e2e/adaptive-playwright-robots-file/actor/Dockerfile b/test/e2e/adaptive-playwright-robots-file/actor/Dockerfilenew file mode 100644index 000000000..f5f5c882e--- /dev/null+++ b/test/e2e/adaptive-playwright-robots-file/actor/Dockerfile@@ -0,0 +1,25 @@+FROM node:20 AS builder++COPY /packages ./packages+COPY /package*.json ./+RUN npm --quiet set progress=false \+ && npm install --only=prod --no-optional --no-audit \+ && npm update++FROM apify/actor-node-playwright-chrome:20-beta++RUN rm -r node_modules+COPY --from=builder /node_modules ./node_modules+COPY --from=builder /packages ./packages+COPY --from=builder /package*.json ./+COPY /.actor ./.actor+COPY /main.js ./++RUN echo "Installed NPM packages:" \+ && (npm list --only=prod --no-optional --all || true) \+ && echo "Node.js version:" \+ && node --version \+ && echo "NPM version:" \+ && npm --version++ENV PLAYWRIGHT_EXECUTABLE_PATH=/usr/bin/google-chromediff --git a/test/e2e/adaptive-playwright-robots-file/actor/main.js b/test/e2e/adaptive-playwright-robots-file/actor/main.jsnew file mode 100644index 000000000..96a87f868--- /dev/null+++ b/test/e2e/adaptive-playwright-robots-file/actor/main.js@@ -0,0 +1,34 @@+import { AdaptivePlaywrightCrawler } from '@crawlee/playwright';+import { Actor } from 'apify';++await Actor.init({+ storage:+ process.env.STORAGE_IMPLEMENTATION === 'LOCAL'+ ? new (await import('@apify/storage-local')).ApifyStorageLocal()+ : undefined,+});++const crawler = new AdaptivePlaywrightCrawler({+ maxRequestsPerCrawl: 10,+ respectRobotsTxtFile: true,+ onSkippedRequest: (args) => crawler.log.warningOnce(`Request ${args.url} was skipped, reason: ${args.reason}`),+});++crawler.router.addDefaultHandler(async ({ log, request, enqueueLinks, pushData }) => {+ log.info(`Processing ${request.loadedUrl}`);+ await enqueueLinks({+ // '/cart' is disallowed by robots.txt+ globs: ['**/cart', '**/collections/*'],+ });+ await pushData({ url: request.url, loadedUrl: request.loadedUrl });+});++await crawler.run([+ 'https://warehouse-theme-metal.myshopify.com',+ 'https://warehouse-theme-metal.myshopify.com/checkout', // '/checkout' is disallowed by robots.txt+]);++const data = await crawler.getData();+console.table(data.items);++await Actor.exit({ exit: Actor.isAtHome() });diff --git a/test/e2e/adaptive-playwright-robots-file/actor/package.json b/test/e2e/adaptive-playwright-robots-file/actor/package.jsonnew file mode 100644index 000000000..144e37179--- /dev/null+++ b/test/e2e/adaptive-playwright-robots-file/actor/package.json@@ -0,0 +1,29 @@+{+ "name": "test-adaptive-playwright-robots-file",+ "version": "0.0.1",+ "description": "Adaptive Playwright Test - Robots file",+ "dependencies": {+ "apify": "next",+ "@apify/storage-local": "^2.1.3",+ "@crawlee/basic": "file:./packages/basic-crawler",+ "@crawlee/browser": "file:./packages/browser-crawler",+ "@crawlee/browser-pool": "file:./packages/browser-pool",+ "@crawlee/core": "file:./packages/core",+ "@crawlee/memory-storage": "file:./packages/memory-storage",+ "@crawlee/playwright": "file:./packages/playwright-crawler",+ "@crawlee/types": "file:./packages/types",+ "@crawlee/utils": "file:./packages/utils",+ "playwright": "*"+ },+ "overrides": {+ "apify": {+ "@crawlee/core": "file:./packages/core",+ "@crawlee/utils": "file:./packages/utils"+ }+ },+ "scripts": {+ "start": "node main.js"+ },+ "type": "module",+ "license": "ISC"+}diff --git a/test/e2e/adaptive-playwright-robots-file/test.mjs b/test/e2e/adaptive-playwright-robots-file/test.mjsnew file mode 100644index 000000000..9edc578f3--- /dev/null+++ b/test/e2e/adaptive-playwright-robots-file/test.mjs@@ -0,0 +1,14 @@+import { initialize, getActorTestDir, runActor, expect } from '../tools.mjs';++const testActorDirname = getActorTestDir(import.meta.url);+await initialize(testActorDirname);++const { datasetItems } = await runActor(testActorDirname, 16384);++const cartRequest = datasetItems.find((item) => item.url === 'https://warehouse-theme-metal.myshopify.com/cart');+const checkoutRequest = datasetItems.find(+ (item) => item.url === 'https://warehouse-theme-metal.myshopify.com/checkout',+);++await expect(!cartRequest, '/cart URL is not processed');+await expect(!checkoutRequest, '/checkout URL is not processed');diff --git a/test/e2e/tools.mjs b/test/e2e/tools.mjsindex 366de3eb4..f332beb69 100644--- a/test/e2e/tools.mjs+++ b/test/e2e/tools.mjs@@ -50,7 +50,7 @@ export function getStorage(dirName) {*/export async function getStats(dirName) {const dir = getStorage(dirName);- const path = join(dir, 'key_value_stores/default/SDK_CRAWLER_STATISTICS_0.json');+ const path = join(dir, `key_value_stores/default/SDK_CRAWLER_STATISTICS_0.json`);if (!existsSync(path)) {return false;