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
refactor: move blocked HTTP status code management to `BasicCrawler` (#3496)
Jindřich Bär8bf2407c1f97
diff --git a/docs/guides/session_management_basic.ts b/docs/guides/session_management_basic.tsindex 1b76177d8..b579f3a31 100644--- a/docs/guides/session_management_basic.ts+++ b/docs/guides/session_management_basic.ts@@ -34,9 +34,6 @@ const crawler = new BasicCrawler({throw e;}- // Automatically retires the session based on response HTTP status code.- session?.retireOnBlockedStatusCodes(response.status);-if ((await response.text()).includes('You are blocked!')) {// You are sure it is blocked.// This will throw away the session.diff --git a/docs/upgrading/upgrading_v4.md b/docs/upgrading/upgrading_v4.mdindex d26f0791e..4a0a4fc1e 100644--- a/docs/upgrading/upgrading_v4.md+++ b/docs/upgrading/upgrading_v4.md@@ -84,9 +84,9 @@ const crawler = new CheerioCrawler({Previously, the crawling context extended a `Record` type, allowing to access any property. This was changed to a strict type, which means that you can only access properties that are defined in the context.-## `additionalBlockedStatusCodes` parameter is removed+## `retireOnBlockedStatusCodes` is removed from `Session`-`additionalBlockedStatusCodes` parameter of `Session.retireOnBlockedStatusCodes` method is removed. Use the `blockedStatusCodes` crawler option instead.+`Session.retireOnBlockedStatusCodes` is removed. Blocked status code handling is now internal to the crawler. Configure blocked status codes via the `blockedStatusCodes` crawler option (moved from `sessionPoolOptions`).## Remove `experimentalContainers` optiondiff --git a/packages/basic-crawler/src/internals/basic-crawler.ts b/packages/basic-crawler/src/internals/basic-crawler.tsindex 93f999559..7ab97aeff 100644--- a/packages/basic-crawler/src/internals/basic-crawler.ts+++ b/packages/basic-crawler/src/internals/basic-crawler.ts@@ -31,6 +31,7 @@ import type {import {AutoscaledPool,bindMethodsToServiceLocator,+ BLOCKED_STATUS_CODES,ContextPipeline,ContextPipelineCleanupError,ContextPipelineInitializationError,@@ -340,6 +341,12 @@ export interface BasicCrawlerOptions<*/statusMessageCallback?: StatusMessageCallback;+ /**+ * HTTP status codes that indicate the session should be retired.+ * @default [401, 403, 429]+ */+ blockedStatusCodes?: number[];+/*** If set to `true`, the crawler will automatically try to bypass any detected bot protection.*@@ -431,6 +438,18 @@ export interface BasicCrawlerOptions<**/id?: string;++ /**+ * An array of HTTP response [Status Codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) to be excluded from error consideration.+ * By default, status codes >= 500 trigger errors.+ */+ ignoreHttpErrorStatusCodes?: number[];++ /**+ * An array of additional HTTP response [Status Codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) to be treated as errors.+ * By default, status codes >= 500 trigger errors.+ */+ additionalHttpErrorStatusCodes?: number[];}/**@@ -551,7 +570,6 @@ export class BasicCrawler</*** A reference to the underlying {@apilink SessionPool} class that manages the crawler's {@apilink Session|sessions}.- * Only available if used by the crawler.*/sessionPool?: SessionPool;@@ -641,6 +659,9 @@ export class BasicCrawler<protected statusMessageLoggingInterval: number;protected statusMessageCallback?: StatusMessageCallback;protected sessionPoolOptions: SessionPoolOptions;+ protected blockedStatusCodes = new Set<number>();+ protected additionalHttpErrorStatusCodes: Set<number>;+ protected ignoreHttpErrorStatusCodes: Set<number>;protected autoscaledPoolOptions: AutoscaledPoolOptions;protected httpClient: BaseHttpClient;protected retryOnBlocked: boolean;@@ -683,6 +704,10 @@ export class BasicCrawler<statusMessageLoggingInterval: ow.optional.number,statusMessageCallback: ow.optional.function,+ additionalHttpErrorStatusCodes: ow.optional.array.ofType(ow.number),+ ignoreHttpErrorStatusCodes: ow.optional.array.ofType(ow.number),++ blockedStatusCodes: ow.optional.array.ofType(ow.number),retryOnBlocked: ow.optional.boolean,respectRobotsTxtFile: ow.optional.any(ow.boolean, ow.object),onSkippedRequest: ow.optional.function,@@ -730,6 +755,9 @@ export class BasicCrawler<sessionPoolOptions = {},proxyConfiguration,+ additionalHttpErrorStatusCodes = [],+ ignoreHttpErrorStatusCodes = [],+// Service locator optionsconfiguration,storageClient,@@ -741,6 +769,7 @@ export class BasicCrawler<maxConcurrency,maxRequestsPerMinute,+ blockedStatusCodes: blockedStatusCodesInput,retryOnBlocked = false,respectRobotsTxtFile = false,onSkippedRequest,@@ -812,6 +841,9 @@ export class BasicCrawler<this.robotsTxtFileCache = new LruCache({ maxLength: 1000 });this.handleSkippedRequest = this.handleSkippedRequest.bind(this);+ this.additionalHttpErrorStatusCodes = new Set([...additionalHttpErrorStatusCodes]);+ this.ignoreHttpErrorStatusCodes = new Set([...ignoreHttpErrorStatusCodes]);+this.requestHandler = requestHandler ?? this.router;this.failedRequestHandler = failedRequestHandler;this.errorHandler = errorHandler;@@ -853,14 +885,8 @@ export class BasicCrawler<...sessionPoolOptions,log: this.log,};- if (this.retryOnBlocked) {- this.sessionPoolOptions.blockedStatusCodes = sessionPoolOptions.blockedStatusCodes ?? [];- if (this.sessionPoolOptions.blockedStatusCodes.length !== 0) {- this.log.warning(- `Both 'blockedStatusCodes' and 'retryOnBlocked' are set. Please note that the 'retryOnBlocked' feature might not work as expected.`,- );- }- }+ this.blockedStatusCodes = new Set(blockedStatusCodesInput ?? BLOCKED_STATUS_CODES);+const maxSignedInteger = 2 ** 31 - 1;if (this.requestHandlerTimeoutMillis > maxSignedInteger) {this.log.warning(@@ -996,6 +1022,19 @@ export class BasicCrawler<}}+ /**+ * Determines if the given HTTP status code is an error status code given+ * the default behaviour and user-set preferences.+ * @param status+ * @returns `true` if the status code is considered an error, `false` otherwise+ */+ protected isErrorStatusCode(status: number): boolean {+ const excludeError = this.ignoreHttpErrorStatusCodes.has(status);+ const includeError = this.additionalHttpErrorStatusCodes.has(status);++ return (status >= 500 && !excludeError) || includeError;+ }+/*** Builds the basic context pipeline that transforms `{ request }` into a full `CrawlingContext`.* This handles base context creation, session resolution, and context helpers.@@ -1704,11 +1743,11 @@ export class BasicCrawler</*** Handles blocked request*/- protected _throwOnBlockedRequest(session: Session, statusCode: number) {- const isBlocked = session.retireOnBlockedStatusCodes(statusCode);+ protected _throwOnBlockedRequest(statusCode: number) {+ if (this.retryOnBlocked) return;- if (isBlocked) {- throw new Error(`Request blocked - received ${statusCode} status code.`);+ if (this.blockedStatusCodes.has(statusCode)) {+ throw new SessionError(`Request blocked - received ${statusCode} status code.`);}}@@ -2117,7 +2156,9 @@ export class BasicCrawler<}if (!request.noRetry) {- request.retryCount++;+ if (!(error instanceof SessionError)) {+ request.retryCount++;+ }const { url, retryCount, id } = request;@@ -2135,6 +2176,10 @@ export class BasicCrawler<}}+ if (error instanceof SessionError) {+ crawlingContext.session?.retire();+ }+// If the request is non-retryable, the error and snapshot aren't saved in the errorTrackerRetry object.// Therefore, we pass the crawlingContext to the errorTracker.add method, enabling snapshot capture.// This is to make sure the error snapshot is not duplicated in the errorTrackerRetry and errorTracker objects.diff --git a/packages/browser-crawler/src/internals/browser-crawler.ts b/packages/browser-crawler/src/internals/browser-crawler.tsindex ecb0d0e81..6cd7ce06d 100644--- a/packages/browser-crawler/src/internals/browser-crawler.ts+++ b/packages/browser-crawler/src/internals/browser-crawler.ts@@ -15,7 +15,6 @@ import type {} from '@crawlee/basic';import {BasicCrawler,- BLOCKED_STATUS_CODES as DEFAULT_BLOCKED_STATUS_CODES,ContextPipeline,cookieStringToToughCookie,enqueueLinks,@@ -434,13 +433,6 @@ export abstract class BrowserCrawler<): Promise<string | false> {const { page, response } = crawlingContext;- const blockedStatusCodes =- // eslint-disable-next-line dot-notation- (this.sessionPool?.['blockedStatusCodes'].length ?? 0) > 0- ? // eslint-disable-next-line dot-notation- this.sessionPool!['blockedStatusCodes']- : DEFAULT_BLOCKED_STATUS_CODES;-// Cloudflare specific heuristic - wait 5 seconds if we get a 403 for the JS challenge to load / resolve.if ((await this.containsSelectors(page, CLOUDFLARE_RETRY_CSS_SELECTORS)) && response?.status() === 403) {await sleep(5000);@@ -453,10 +445,10 @@ export abstract class BrowserCrawler<}const foundSelectors = await this.containsSelectors(page, RETRY_CSS_SELECTORS);- const blockedStatusCode = blockedStatusCodes.find((x) => x === (response?.status() ?? 0));+ const statusCode = response?.status() ?? 0;if (foundSelectors) return `Found selectors: ${foundSelectors.join(', ')}`;- if (blockedStatusCode) return `Received blocked status code: ${blockedStatusCode}`;+ if (this.blockedStatusCodes.has(statusCode)) return `Received blocked status code: ${statusCode}`;return false;}@@ -668,11 +660,19 @@ export abstract class BrowserCrawler<const status: number = response.status();this.stats.registerStatusCode(status);++ if (this.isErrorStatusCode(status)) {+ if (this.additionalHttpErrorStatusCodes.has(status)) {+ throw new Error(`${status} - Error status code was set by user.`);+ }++ throw new Error(`${status} - Internal Server Error`);+ }}if (this.sessionPool && response && session) {if (typeof response === 'object' && typeof response.status === 'function') {- this._throwOnBlockedRequest(session, response.status());+ this._throwOnBlockedRequest(response.status());} else {this.log.debug('Got a malformed Browser response.', { request, response });}diff --git a/packages/core/src/session_pool/session.ts b/packages/core/src/session_pool/session.tsindex d736f8347..7d7efe3a7 100644--- a/packages/core/src/session_pool/session.ts+++ b/packages/core/src/session_pool/session.ts@@ -288,23 +288,6 @@ export class Session implements ISession {this._maybeSelfRetire();}- /**- * With certain status codes: `401`, `403` or `429` we can be certain- * that the target website is blocking us. This function helps to do this conveniently- * by retiring the session when such code is received. Optionally, the default status- * codes can be extended in the second parameter.- * @param statusCode HTTP status code.- * @returns Whether the session was retired.- */- retireOnBlockedStatusCodes(statusCode: number): boolean {- // eslint-disable-next-line dot-notation -- accessing private property- const isBlocked = this.sessionPool['blockedStatusCodes'].includes(statusCode);- if (isBlocked) {- this.retire();- }- return isBlocked;- }-/*** Saves cookies from an HTTP response to be used with the session.* It expects an object with a `headers` property that's either an `Object`diff --git a/packages/core/src/session_pool/session_pool.ts b/packages/core/src/session_pool/session_pool.tsindex 3c8210e31..c6e310276 100644--- a/packages/core/src/session_pool/session_pool.ts+++ b/packages/core/src/session_pool/session_pool.ts@@ -10,7 +10,7 @@ import { EventType } from '../events/event_manager.js';import type { CrawleeLogger } from '../log.js';import { serviceLocator } from '../service_locator.js';import { KeyValueStore } from '../storages/key_value_store.js';-import { BLOCKED_STATUS_CODES, MAX_POOL_SIZE, PERSIST_STATE_KEY } from './consts.js';+import { MAX_POOL_SIZE, PERSIST_STATE_KEY } from './consts.js';import type { SessionOptions } from './session.js';import { Session } from './session.js';@@ -51,13 +51,6 @@ export interface SessionPoolOptions {*/createSessionFunction?: CreateSession;- /**- * Specifies which response status codes are considered as blocked.- * Session connected to such request will be marked as retired.- * @default [401, 403, 429]- */- blockedStatusCodes?: number[];-/** @internal */log?: CrawleeLogger;@@ -133,7 +126,6 @@ export class SessionPool extends EventEmitter {protected persistStateKey: string;protected _listener!: () => Promise<void>;protected events: EventManager;- protected readonly blockedStatusCodes: number[];protected persistenceOptions: PersistenceOptions;protected isInitialized = false;@@ -153,7 +145,6 @@ export class SessionPool extends EventEmitter {persistStateKey: ow.optional.string,createSessionFunction: ow.optional.function,sessionOptions: ow.optional.object,- blockedStatusCodes: ow.optional.array.ofType(ow.number),log: ow.optional.object,persistenceOptions: ow.optional.object,}),@@ -165,14 +156,12 @@ export class SessionPool extends EventEmitter {persistStateKey = PERSIST_STATE_KEY,createSessionFunction,sessionOptions = {},- blockedStatusCodes = BLOCKED_STATUS_CODES,log = serviceLocator.getLogger(),persistenceOptions = {enable: true,},} = options;- this.blockedStatusCodes = blockedStatusCodes;this.events = serviceLocator.getEventManager();this.log = log.child({ prefix: 'SessionPool' });this.persistenceOptions = persistenceOptions;diff --git a/packages/http-crawler/src/internals/http-crawler.ts b/packages/http-crawler/src/internals/http-crawler.tsindex 8cf405b9b..131b999d1 100644--- a/packages/http-crawler/src/internals/http-crawler.ts+++ b/packages/http-crawler/src/internals/http-crawler.ts@@ -16,15 +16,7 @@ import type {RoutesFromSchemas,Session,} from '@crawlee/basic';-import {- BasicCrawler,- BLOCKED_STATUS_CODES,- ContextPipeline,- mergeCookies,- RequestState,- Router,- SessionError,-} from '@crawlee/basic';+import { BasicCrawler, ContextPipeline, mergeCookies, RequestState, Router, SessionError } from '@crawlee/basic';import type { LoadedRequest } from '@crawlee/core';import { ResponseWithUrl } from '@crawlee/http-client';import type { Awaitable, Dictionary } from '@crawlee/types';@@ -146,18 +138,6 @@ export interface HttpCrawlerOptions<* It passes the "Cookie" header to the request with the session cookies.*/persistCookiesPerSession?: boolean;-- /**- * An array of HTTP response [Status Codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) to be excluded from error consideration.- * By default, status codes >= 500 trigger errors.- */- ignoreHttpErrorStatusCodes?: number[];-- /**- * An array of additional HTTP response [Status Codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) to be treated as errors.- * By default, status codes >= 500 trigger errors.- */- additionalHttpErrorStatusCodes?: number[];}/**@@ -325,8 +305,6 @@ export class HttpCrawler<protected ignoreSslErrors: boolean;protected suggestResponseEncoding?: string;protected forceResponseEncoding?: string;- protected additionalHttpErrorStatusCodes: Set<number>;- protected ignoreHttpErrorStatusCodes: Set<number>;protected readonly supportedMimeTypes: Set<string>;protected static override optionsShape = {@@ -339,9 +317,6 @@ export class HttpCrawler<forceResponseEncoding: ow.optional.string,persistCookiesPerSession: ow.optional.boolean,- additionalHttpErrorStatusCodes: ow.optional.array.ofType(ow.number),- ignoreHttpErrorStatusCodes: ow.optional.array.ofType(ow.number),-preNavigationHooks: ow.optional.array,postNavigationHooks: ow.optional.array,};@@ -364,8 +339,6 @@ export class HttpCrawler<persistCookiesPerSession = true,preNavigationHooks = [],postNavigationHooks = [],- additionalHttpErrorStatusCodes = [],- ignoreHttpErrorStatusCodes = [],// BasicCrawlerautoscaledPoolOptions = HTTP_OPTIMIZED_AUTOSCALED_POOL_OPTIONS,@@ -394,8 +367,6 @@ export class HttpCrawler<this.ignoreSslErrors = ignoreSslErrors;this.suggestResponseEncoding = suggestResponseEncoding;this.forceResponseEncoding = forceResponseEncoding;- this.additionalHttpErrorStatusCodes = new Set([...additionalHttpErrorStatusCodes]);- this.ignoreHttpErrorStatusCodes = new Set([...ignoreHttpErrorStatusCodes]);this.preNavigationHooks = preNavigationHooks;this.postNavigationHooks = [({ request, response }) => this._abortDownloadOfBody(request, response!),@@ -514,7 +485,7 @@ export class HttpCrawler<return $;};- this._throwOnBlockedRequest(crawlingContext.session, response.status!);+ this._throwOnBlockedRequest(response.status);if (this.persistCookiesPerSession) {crawlingContext.session.setCookiesFromResponse(response);@@ -552,14 +523,7 @@ export class HttpCrawler<}}- const blockedStatusCodes =- // eslint-disable-next-line dot-notation- (this.sessionPool?.['blockedStatusCodes'].length ?? 0) > 0- ? // eslint-disable-next-line dot-notation- this.sessionPool!['blockedStatusCodes']- : BLOCKED_STATUS_CODES;-- if (blockedStatusCodes.includes(crawlingContext.response.status!)) {+ if (this.blockedStatusCodes.has(crawlingContext.response.status!)) {return `Blocked by status code ${crawlingContext.response.status}`;}@@ -624,10 +588,7 @@ export class HttpCrawler<this.stats.registerStatusCode(status);}- const excludeError = this.ignoreHttpErrorStatusCodes.has(status);- const includeError = this.additionalHttpErrorStatusCodes.has(status);-- if ((status >= 500 && !excludeError) || includeError) {+ if (this.isErrorStatusCode(status)) {const body = await reencodedResponse.text(); // TODO - this always uses UTF-8 (see https://developer.mozilla.org/en-US/docs/Web/API/Request/text)// Errors are often sent as JSON, so attempt to parse them,@@ -639,7 +600,7 @@ export class HttpCrawler<throw new Error(`${status} - ${message}`);}- if (includeError) {+ if (this.additionalHttpErrorStatusCodes.has(status)) {throw new Error(`${status} - Error status code was set by user.`);}@@ -767,10 +728,7 @@ export class HttpCrawler<const { status } = response;const { type } = parseContentTypeFromResponse(response);- // eslint-disable-next-line dot-notation -- accessing private property- const blockedStatusCodes = this.sessionPool ? this.sessionPool['blockedStatusCodes'] : [];- // if we retry the request, can the Content-Type change?- const isTransientContentType = status >= 500 || blockedStatusCodes.includes(status);+ const isTransientContentType = status >= 500 || this.blockedStatusCodes.has(status);if (!this.supportedMimeTypes.has(type) && !this.supportedMimeTypes.has('*/*') && !isTransientContentType) {request.noRetry = true;diff --git a/packages/playwright-crawler/src/internals/playwright-crawler.ts b/packages/playwright-crawler/src/internals/playwright-crawler.tsindex b58e581f9..3c21f059b 100644--- a/packages/playwright-crawler/src/internals/playwright-crawler.ts+++ b/packages/playwright-crawler/src/internals/playwright-crawler.ts@@ -303,8 +303,8 @@ export class PlaywrightCrawler<return playwrightUtils.handleCloudflareChallenge(context.page,context.request.url,- context.session,options,+ this.blockedStatusCodes,);},};diff --git a/packages/playwright-crawler/src/internals/utils/playwright-utils.ts b/packages/playwright-crawler/src/internals/utils/playwright-utils.tsindex a02ad22b8..8665a198a 100644--- a/packages/playwright-crawler/src/internals/utils/playwright-utils.ts+++ b/packages/playwright-crawler/src/internals/utils/playwright-utils.ts@@ -22,15 +22,7 @@ import { readFile } from 'node:fs/promises';import { createRequire } from 'node:module';import vm from 'node:vm';-import {- Configuration,- KeyValueStore,- type Request,- serviceLocator,- type Session,- SessionError,- validators,-} from '@crawlee/browser';+import { Configuration, KeyValueStore, type Request, serviceLocator, SessionError, validators } from '@crawlee/browser';import type { BatchAddRequestsResult } from '@crawlee/types';import { type CheerioRoot, type Dictionary, expandShadowRoots, sleep } from '@crawlee/utils';import * as cheerio from 'cheerio';@@ -728,23 +720,17 @@ export interface HandleCloudflareChallengeOptions {** @param page Playwright [`Page`](https://playwright.dev/docs/api/class-page) object* @param url current URL for request identification, only used for logging- * @param [session] current session object* @param [options]*/async function handleCloudflareChallenge(page: Page,url: string,- session?: Session,options: HandleCloudflareChallengeOptions = {},+ blockedStatusCodes?: Set<number>,): Promise<void> {- // eslint-disable-next-line dot-notation- const blockedStatusCodes = session?.['sessionPool']['blockedStatusCodes'] as number[];-- // Cloudflare pages are 403, which are blocked by default- if (blockedStatusCodes?.includes(403)) {- const idx = blockedStatusCodes.indexOf(403);- blockedStatusCodes.splice(idx, 1);- }+ // Cloudflare pages return 403, which is blocked by default — temporarily allow it during challenge handling+ const had403 = blockedStatusCodes?.has(403);+ blockedStatusCodes?.delete(403);options.isBlockedCallback ??= async () => {const isBlocked = await page.evaluate(() => {@@ -774,78 +760,87 @@ async function handleCloudflareChallenge(return options.isChallengeCallback!(page).catch(() => false);};- if (!(await isChallenge())) {- await retryBlocked();- return;- }+ try {+ if (!(await isChallenge())) {+ await retryBlocked();+ return;+ }- const logLevel = options.verbose ? 'info' : 'debug';- getLog()[logLevel](- `Detected Cloudflare challenge at ${url}, trying to solve it. This can take up to ${10 + (options.sleepSecs ?? 10)} seconds.`,- );+ const logLevel = options.verbose ? 'info' : 'debug';+ getLog()[logLevel](+ `Detected Cloudflare challenge at ${url}, trying to solve it. This can take up to ${10 + (options.sleepSecs ?? 10)} seconds.`,+ );- const bb = await page- .evaluate(() => {- // Prefer the actual challenge widget (the box holding the Turnstile checkbox input);- // fall back to the first content div for older challenge layouts.- const div =- document.querySelector('.main-content div:has(input[id^="cf-chl-widget-"])') ??- document.querySelector('.main-content div');- return div?.getBoundingClientRect();- })- .catch(() => undefined);-- if (!bb) {- return;- }+ const bb = await page+ .evaluate(() => {+ // Prefer the actual challenge widget (the box holding the Turnstile checkbox input);+ // fall back to the first content div for older challenge layouts.+ const div =+ document.querySelector('.main-content div:has(input[id^="cf-chl-widget-"])') ??+ document.querySelector('.main-content div');+ return div?.getBoundingClientRect();+ })+ .catch(() => undefined);++ if (!bb) {+ return;+ }- const randomOffset = (range: number) => {- return Math.round(100 * range * Math.random()) / 100;- };+ const randomOffset = (range: number) => {+ return Math.round(100 * range * Math.random()) / 100;+ };- let x = bb.x + 30;- let y = bb.y + 25;+ let x = bb.x + 30;+ let y = bb.y + 25;- // try to click the checkbox every second- for (let i = 0; i < 10; i++) {- await sleep((options.preChallengeSleepSecs ?? 1) * 1000);+ // try to click the checkbox every second+ for (let i = 0; i < 10; i++) {+ await sleep((options.preChallengeSleepSecs ?? 1) * 1000);- // break early if we are no longer on the CF challenge page- if (!(await isChallenge())) {- break;- }+ // break early if we are no longer on the CF challenge page+ if (!(await isChallenge())) {+ break;+ }- if (options.clickPositionCallback) {- const pos = await options.clickPositionCallback(page);- if (pos) {- x = pos.x;- y = pos.y;+ if (options.clickPositionCallback) {+ const pos = await options.clickPositionCallback(page);+ if (pos) {+ x = pos.x;+ y = pos.y;+ }}- }- if (options.clickCallback) {- await options.clickCallback(page, { x, y });- continue;- }+ if (options.clickCallback) {+ await options.clickCallback(page, { x, y });+ continue;+ }- // we can click on the text too, so X can be a bit larger- const xRandomized = x + randomOffset(10);- const yRandomized = y + randomOffset(10);+ // we can click on the text too, so X can be a bit larger+ const xRandomized = x + randomOffset(10);+ const yRandomized = y + randomOffset(10);- getLog()[logLevel](`Trying to click on the Cloudflare checkbox at ${url}`, { x: xRandomized, y: yRandomized });- await page.mouse.click(xRandomized, yRandomized);+ getLog()[logLevel](`Trying to click on the Cloudflare checkbox at ${url}`, {+ x: xRandomized,+ y: yRandomized,+ });+ await page.mouse.click(xRandomized, yRandomized);- // sometimes the checkbox is lower (could be caused by a lag when rendering the logo)- await page.mouse.click(xRandomized, yRandomized + 35);- }+ // sometimes the checkbox is lower (could be caused by a lag when rendering the logo)+ await page.mouse.click(xRandomized, yRandomized + 35);+ }- await sleep((options.sleepSecs ?? 10) * 1000);+ await sleep((options.sleepSecs ?? 10) * 1000);- if (await isChallenge()) {- throw new SessionError(`Blocked by Cloudflare when processing ${url}`);- }+ if (await isChallenge()) {+ throw new SessionError(`Blocked by Cloudflare when processing ${url}`);+ }- await retryBlocked();+ await retryBlocked();+ } finally {+ if (had403) {+ blockedStatusCodes?.add(403);+ }+ }}/** @internal */diff --git a/packages/types/src/session.ts b/packages/types/src/session.tsindex 7bca512c9..5427db68b 100644--- a/packages/types/src/session.ts+++ b/packages/types/src/session.ts@@ -157,16 +157,6 @@ export interface ISession {*/markBad(): void;- /**- * With certain status codes: `401`, `403` or `429` we can be certain- * that the target website is blocking us. This function helps to do this conveniently- * by retiring the session when such code is received. Optionally, the default status- * codes can be extended in the second parameter.- * @param statusCode HTTP status code.- * @returns Whether the session was retired.- */- retireOnBlockedStatusCodes(statusCode: number): boolean;-/*** Saves cookies from an HTTP response to be used with the session.* It expects an object with a `headers` property that's either an `Object`diff --git a/test/core/crawlers/cheerio_crawler.test.ts b/test/core/crawlers/cheerio_crawler.test.tsindex 856f5d72e..f70d59eb9 100644--- a/test/core/crawlers/cheerio_crawler.test.ts+++ b/test/core/crawlers/cheerio_crawler.test.ts@@ -923,6 +923,7 @@ describe('CheerioCrawler', () => {for (const code of [401, 403, 429]) {const failed: Request[] = [];const sessions: Session[] = [];+ const maxSessionRotations = 5;const crawler = new CheerioCrawler({requestList: await getRequestListForMock({statusCode: code,@@ -931,7 +932,8 @@ describe('CheerioCrawler', () => {}),persistCookiesPerSession: false,- maxRequestRetries: 0,+ maxRequestRetries: 10,+ maxSessionRotations,requestHandler: ({ session }) => {sessions.push(session!);},@@ -942,10 +944,12 @@ describe('CheerioCrawler', () => {await crawler.run();// @ts-expect-error private symbol- expect(crawler.sessionPool.sessions.length).toBe(4);- // @ts-expect-error private symbol+ const poolSessions: Session[] = crawler.sessionPool.sessions;+ // each request is retried with session rotation (maxSessionRotations times), so we get+ // (maxSessionRotations + 1) sessions per request (rotated ones + the final one)+ expect(poolSessions.length).toBe(4 * (maxSessionRotations + 1));- crawler.sessionPool.sessions.forEach((session) => {+ poolSessions.forEach((session) => {expect(session.errorScore).toBeGreaterThanOrEqual(session.maxErrorScore);});diff --git a/test/core/crawlers/http_crawler.test.ts b/test/core/crawlers/http_crawler.test.tsindex ba834ecb9..fc692bde9 100644--- a/test/core/crawlers/http_crawler.test.ts+++ b/test/core/crawlers/http_crawler.test.ts@@ -381,11 +381,12 @@ test('should retry on 403 even with disallowed content-type', async () => {const crawler = new HttpCrawler({maxConcurrency: 1,maxRequestRetries: 1,+ maxSessionRotations: 1,preNavigationHooks: [async ({ request }) => {// mock 403 response with octet stream on first request attempt, but not on// subsequent retries, so the request should eventually succeed- if (request.retryCount === 0) {+ if (request.sessionRotationCount === 0) {request.url = `${url}/403-with-octet-stream`;} else {request.url = url;@@ -400,7 +401,7 @@ test('should retry on 403 even with disallowed content-type', async () => {await crawler.run([url]);expect(succeeded).toHaveLength(1);- expect(succeeded[0].retryCount).toBe(1);+ expect(succeeded[0].sessionRotationCount).toBe(1);});test('works with a custom HttpClient', async () => {diff --git a/test/core/session_pool/session.test.ts b/test/core/session_pool/session.test.tsindex 7cbd32da0..99de81377 100644--- a/test/core/session_pool/session.test.ts+++ b/test/core/session_pool/session.test.ts@@ -155,25 +155,6 @@ describe('Session - testing session behaviour ', () => {expect(session.cookieJar.setCookie).toBeDefined();});- test('should checkStatus work', () => {- session = new Session({ sessionPool });- expect(session.retireOnBlockedStatusCodes(100)).toBeFalsy();- expect(session.retireOnBlockedStatusCodes(200)).toBeFalsy();- expect(session.retireOnBlockedStatusCodes(400)).toBeFalsy();- expect(session.retireOnBlockedStatusCodes(500)).toBeFalsy();- // @ts-expect-error- sessionPool.blockedStatusCodes.forEach((status) => {- const sess = new Session({ sessionPool });- let isCalled;- const call = () => {- isCalled = true;- };- sess.retire = call;- expect(sess.retireOnBlockedStatusCodes(status)).toBeTruthy();- expect(isCalled).toBeTruthy();- });- });-test('setCookies should work', () => {const url = 'https://example.com';const cookies = [diff --git a/website/versioned_docs/version-4.0/guides/session_management_basic.ts b/website/versioned_docs/version-4.0/guides/session_management_basic.tsindex 38b65ee9d..a51e6437b 100644--- a/website/versioned_docs/version-4.0/guides/session_management_basic.ts+++ b/website/versioned_docs/version-4.0/guides/session_management_basic.ts@@ -36,9 +36,6 @@ const crawler = new BasicCrawler({throw e;}- // Automatically retires the session based on response HTTP status code.- session?.retireOnBlockedStatusCodes(response.status);-if ((await response.text()).includes('You are blocked!')) {// You are sure it is blocked.// This will throw away the session.diff --git a/website/versioned_docs/version-4.0/upgrading/upgrading_v4.md b/website/versioned_docs/version-4.0/upgrading/upgrading_v4.mdindex d26f0791e..f15cf046b 100644--- a/website/versioned_docs/version-4.0/upgrading/upgrading_v4.md+++ b/website/versioned_docs/version-4.0/upgrading/upgrading_v4.md@@ -84,9 +84,9 @@ const crawler = new CheerioCrawler({Previously, the crawling context extended a `Record` type, allowing to access any property. This was changed to a strict type, which means that you can only access properties that are defined in the context.-## `additionalBlockedStatusCodes` parameter is removed+## `retireOnBlockedStatusCodes` is removed from `Session`-`additionalBlockedStatusCodes` parameter of `Session.retireOnBlockedStatusCodes` method is removed. Use the `blockedStatusCodes` crawler option instead.+`Session.retireOnBlockedStatusCodes` is removed. Blocked status code handling is now internal to the crawler. Configure blocked status codes via the `blockedStatusCodes` crawler option (moved from `sessionPoolOptions`). `ignoreHttpErrorStatusCodes` in `HttpCrawler` now also excludes matching codes from the blocked status codes list.## Remove `experimentalContainers` option