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: Introduce IRenderingTypePredictor and unify the ownership pattern (#3944)
Jan Buchar9bde1e630548
diff --git a/docs/public-api/crawlee-playwright.api.md b/docs/public-api/crawlee-playwright.api.mdindex ee2b305ad..d0d132e15 100644--- a/docs/public-api/crawlee-playwright.api.md+++ b/docs/public-api/crawlee-playwright.api.md@@ -108,7 +108,7 @@ export interface AdaptivePlaywrightCrawlerOptions<ContextExtension = Dictionary_preNavigationHooks?: AdaptiveHook<ContextExtension>[];preventDirectStorageAccess?: boolean;renderingTypeDetectionRatio?: number;- renderingTypePredictor?: Pick<RenderingTypePredictor, 'predict' | 'storeResult' | 'initialize'>;+ renderingTypePredictor?: IRenderingTypePredictor;resultChecker?: (result: RequestHandlerResult) => boolean;resultComparator?: (resultA: RequestHandlerResult, resultB: RequestHandlerResult) => boolean | 'equal' | 'different' | 'inconclusive';shouldPropagateError?: (error: Error, context: PlaywrightCrawlingContext) => Awaitable<boolean>;@@ -234,6 +234,15 @@ function injectJQuery(page: Page, options?: {surviveNavigations?: boolean;}): Promise<unknown>;+// @public+export interface IRenderingTypePredictor {+ predict(request: Request_2): {+ renderingType: RenderingType;+ detectionProbabilityRecommendation: number;+ };+ storeResult(requests: Request_2 | Request_2[], renderingType: RenderingType): void;+}+// @publicexport function launchPlaywright(launchContext?: PlaywrightLaunchContext, configuration?: Configuration): Promise<Browser>;@@ -390,7 +399,7 @@ declare namespace playwrightUtils {export type RenderingType = 'clientOnly' | 'static';// @public-export class RenderingTypePredictor {+export class RenderingTypePredictor implements IRenderingTypePredictor {constructor(input: RenderingTypePredictorOptions);initialize(): Promise<void>;predict(input: Request_2): {diff --git a/docs/upgrading/upgrading_v4.md b/docs/upgrading/upgrading_v4.mdindex 7c46eec0d..7463b4c30 100644--- a/docs/upgrading/upgrading_v4.md+++ b/docs/upgrading/upgrading_v4.md@@ -355,6 +355,29 @@ await pool.destroy();Note that this couples your code to the built-in `BrowserPool` — custom `IBrowserPool` implementations may not expose controllers at all.+## Custom rendering type predictors via the `IRenderingTypePredictor` interface++The `renderingTypePredictor` option of `AdaptivePlaywrightCrawler` is now typed as the new `IRenderingTypePredictor` interface — `predict(request)` and `storeResult(requests, renderingType)`, nothing else. The built-in `RenderingTypePredictor` implements it, so passing one still works.++What changed is the lifecycle: the crawler used to call `initialize()` on the predictor it was given, even though it did not create it. It now follows the same own-only-what-you-built rule as the session and browser pools — a predictor you pass in is *borrowed*, so setting it up is your job, and `initialize` is not part of the interface at all. The built-in predictor restores its persisted state in `initialize()` and will throw `Recoverable state has not yet been loaded` from `predict()` if it is never called:++```typescript+import { AdaptivePlaywrightCrawler, RenderingTypePredictor } from '@crawlee/playwright';++const renderingTypePredictor = new RenderingTypePredictor({ detectionRatio: 0.1 });+// You own the predictor — initialize it yourself (this used to be done by the crawler).+await renderingTypePredictor.initialize();++const crawler = new AdaptivePlaywrightCrawler({+ renderingTypePredictor,+ requestHandler: async ({ pushData }) => {+ // …+ },+});+```++If you don't pass a predictor, nothing changes: the crawler builds one from `renderingTypeDetectionRatio` and, since it owns that one, initializes it for you.+## `tieredProxyUrls` is removed from `ProxyConfiguration`The `tieredProxyUrls` option has been removed, together with the `proxyTier` field on `ProxyInfo` and the `proxyTier` plumbing in `BrowserPool`. In v4 the `Session` is the main rotation unit - a session already carries its own proxy, cookies and error score, so the pool rotates the whole fingerprint when a session gets retired on a block.diff --git a/packages/playwright-crawler/src/index.ts b/packages/playwright-crawler/src/index.tsindex e745ea76b..9607b713b 100644--- a/packages/playwright-crawler/src/index.ts+++ b/packages/playwright-crawler/src/index.ts@@ -7,4 +7,4 @@ export { RenderingTypePredictor } from './internals/utils/rendering-type-predictexport * as playwrightUtils from './internals/utils/playwright-utils.js';export * as playwrightClickElements from './internals/enqueue-links/click-elements.js';export type { DirectNavigationOptions as PlaywrightDirectNavigationOptions } from './internals/utils/playwright-utils.js';-export type { RenderingType } from './internals/utils/rendering-type-prediction.js';+export type { IRenderingTypePredictor, RenderingType } from './internals/utils/rendering-type-prediction.js';diff --git a/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts b/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.tsindex 8152e448d..ca8c5d9be 100644--- a/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts+++ b/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts@@ -27,6 +27,7 @@ import type {StatisticState,} from '@crawlee/core';import {+ OwnedOrInjected,RequestHandlerError,RequestHandlerResult,resolveBaseUrlForEnqueueLinksFiltering,@@ -46,7 +47,11 @@ import { addTimeoutToPromise } from '@apify/timeout';import type { PlaywrightCrawlingContext, PlaywrightGotoOptions, PlaywrightHook } from './playwright-crawler.js';import { PlaywrightCrawler } from './playwright-crawler.js';-import { type RenderingType, RenderingTypePredictor } from './utils/rendering-type-prediction.js';+import {+ type IRenderingTypePredictor,+ type RenderingType,+ RenderingTypePredictor,+} from './utils/rendering-type-prediction.js';type Result<TResult> =| { result: TResult; ok: true; logs?: LogProxyCall[] }@@ -254,9 +259,11 @@ export interface AdaptivePlaywrightCrawlerOptions<) => boolean | 'equal' | 'different' | 'inconclusive';/**- * A custom rendering type predictor+ * A custom rendering type predictor. A predictor passed here is borrowed - the crawler never drives its+ * lifecycle, so set it up yourself (the built-in {@apilink RenderingTypePredictor} needs `initialize()`).+ * Omit the option and the crawler builds its own from `renderingTypeDetectionRatio` - and initializes it.*/- renderingTypePredictor?: Pick<RenderingTypePredictor, 'predict' | 'storeResult' | 'initialize'>;+ renderingTypePredictor?: IRenderingTypePredictor;/*** Prevent direct access to storage in request handlers (only allow using context helpers).@@ -315,7 +322,7 @@ export class AdaptivePlaywrightCrawler<GetUserDataFromRequest<AdaptivePlaywrightCrawlerContext['request']>>,> extends BasicCrawler<AdaptivePlaywrightCrawlerContext, ContextExtension, ExtendedContext, Routes> {- private renderingTypePredictor: NonNullable<AdaptivePlaywrightCrawlerOptions['renderingTypePredictor']>;+ private renderingTypePredictor: OwnedOrInjected<IRenderingTypePredictor, RenderingTypePredictor>;private resultChecker: NonNullable<AdaptivePlaywrightCrawlerOptions['resultChecker']>;private shouldPropagateError: NonNullable<AdaptivePlaywrightCrawlerOptions['shouldPropagateError']>;private resultComparator: NonNullable<AdaptivePlaywrightCrawlerOptions['resultComparator']>;@@ -358,8 +365,12 @@ export class AdaptivePlaywrightCrawler<});this.individualRequestHandlerTimeoutMillis = requestHandlerTimeoutSecs * 1000;- this.renderingTypePredictor =- renderingTypePredictor ?? new RenderingTypePredictor({ detectionRatio: renderingTypeDetectionRatio });+ // `renderingTypeDetectionRatio` only configures the default predictor - an injected one brings its own+ // detection ratio (and its own state), so the option is ignored in that case.+ this.renderingTypePredictor = OwnedOrInjected.resolve<IRenderingTypePredictor, RenderingTypePredictor>(+ renderingTypePredictor,+ () => new RenderingTypePredictor({ detectionRatio: renderingTypeDetectionRatio }),+ );this.resultChecker = resultChecker ?? (() => true);this.shouldPropagateError = shouldPropagateError ?? (() => false);@@ -425,7 +436,9 @@ export class AdaptivePlaywrightCrawler<}protected override async _init(): Promise<void> {- await this.renderingTypePredictor.initialize();+ // Only the predictor we built ourselves is ours to initialize - an injected one is borrowed, so its+ // lifecycle (including restoring persisted state) stays with whoever created it.+ await this.renderingTypePredictor.ifOwned((predictor) => predictor.initialize());return await super._init();}@@ -617,7 +630,7 @@ export class AdaptivePlaywrightCrawler<}protected override async runRequestHandler(crawlingContext: CrawlingContext): Promise<void> {- const renderingTypePrediction = this.renderingTypePredictor.predict(crawlingContext.request);+ const renderingTypePrediction = this.renderingTypePredictor.value.predict(crawlingContext.request);const shouldDetectRenderingType = Math.random() < renderingTypePrediction.detectionProbabilityRecommendation;if (!shouldDetectRenderingType) {@@ -736,7 +749,7 @@ export class AdaptivePlaywrightCrawler<);if (detectionResult !== undefined) {- this.renderingTypePredictor.storeResult(crawlingContext.request, detectionResult);+ this.renderingTypePredictor.value.storeResult(crawlingContext.request, detectionResult);}}} finally {diff --git a/packages/playwright-crawler/src/internals/utils/rendering-type-prediction.ts b/packages/playwright-crawler/src/internals/utils/rendering-type-prediction.tsindex d750d33c3..a7b4c4e5e 100644--- a/packages/playwright-crawler/src/internals/utils/rendering-type-prediction.ts+++ b/packages/playwright-crawler/src/internals/utils/rendering-type-prediction.ts@@ -46,12 +46,29 @@ export interface RenderingTypePredictorOptions {persistenceOptions?: Partial<RecoverableStatePersistenceOptions>;}+/**+ * Minimal contract that any object passed to {@apilink AdaptivePlaywrightCrawler} as its+ * `renderingTypePredictor` option must satisfy.+ *+ * @experimental+ */+export interface IRenderingTypePredictor {+ /** Predict the rendering type for a request, and how likely the crawler should be to verify it. */+ predict(request: Request): {+ renderingType: RenderingType;+ detectionProbabilityRecommendation: number;+ };++ /** Report a detected rendering type, so that future predictions can take it into account. */+ storeResult(requests: Request | Request[], renderingType: RenderingType): void;+}+/*** Stores rendering type information for previously crawled URLs and predicts the rendering type for URLs that have yet to be crawled and recommends when rendering type detection should be performed.** @experimental*/-export class RenderingTypePredictor {+export class RenderingTypePredictor implements IRenderingTypePredictor {private detectionRatio: number;private state: RecoverableState<{logreg: LogisticRegression;diff --git a/test/core/crawlers/adaptive_playwright_crawler.test.ts b/test/core/crawlers/adaptive_playwright_crawler.test.tsindex 300912734..1a71da540 100644--- a/test/core/crawlers/adaptive_playwright_crawler.test.ts+++ b/test/core/crawlers/adaptive_playwright_crawler.test.ts@@ -162,7 +162,6 @@ describe('AdaptivePlaywrightCrawler', () => {detectionProbabilityRecommendation: number;renderingType: 'clientOnly' | 'static';}) => ({- initialize: async () => {},predict: vi.fn((_request: Request) => prediction),storeResult: vi.fn((_request: Request, _renderingType: string) => {}),});@@ -761,16 +760,20 @@ describe('AdaptivePlaywrightCrawler', () => {await pushData({ content: 'test data' });});+ // Use a real RenderingTypePredictor instead of the mocked one. An injected predictor is borrowed -+ // the crawler never initializes it, so restoring its persisted state is up to us.+ const renderingTypePredictor = new RenderingTypePredictor({ detectionRatio: 1 });+ await renderingTypePredictor.initialize();+const crawler = await makeOneshotCrawler({requestHandler,- // Use a real RenderingTypePredictor instead of the mocked one- renderingTypePredictor: new RenderingTypePredictor({ detectionRatio: 1 }),+ renderingTypePredictor,},[`http://${HOSTNAME}:${port}/static`],);- // Run the crawler - this will initialize the RenderingTypePredictor and potentially store results+ // Run the crawler - this will potentially store rendering type detection resultsawait crawler.run();// Now emit a PERSIST_STATE event to trigger state persistence@@ -799,6 +802,55 @@ describe('AdaptivePlaywrightCrawler', () => {await expect(newPredictor.initialize()).resolves.not.toThrow();});+ describe('rendering type predictor lifecycle', () => {+ const requestHandler: AdaptivePlaywrightCrawlerOptions['requestHandler'] = async ({ pushData }) => {+ await pushData({ content: 'test data' });+ };++ test('initializes the default predictor it built itself', async () => {+ const crawler = new AdaptivePlaywrightCrawler({+ requestHandler,+ // No `renderingTypePredictor` - the crawler builds (and therefore owns) its own.+ renderingTypeDetectionRatio: 1,+ maxConcurrency: 1,+ maxRequestRetries: 0,+ maxRequestsPerCrawl: 1,+ requestList: await RequestList.open({ sources: [`http://${HOSTNAME}:${port}/static`] }),+ });++ await crawler.run();++ // Persistence only happens for an initialized predictor, so a stored state proves the crawler+ // did initialize the predictor it owns.+ serviceLocator.getEventManager().emit(EventType.PERSIST_STATE);+ await sleep(100);++ const store = await KeyValueStore.open();+ await expect(store.getValue<string>('rendering-type-predictor-state')).resolves.not.toBeNull();+ });++ test('does not initialize an injected predictor', async () => {+ const renderingTypePredictor = {+ ...makeRiggedRenderingTypePredictor({+ detectionProbabilityRecommendation: 0,+ renderingType: 'static',+ }),+ // Not part of the predictor contract the crawler depends on - a borrowed instance is set up by+ // whoever created it, so the crawler must keep its hands off.+ initialize: vi.fn(async () => {}),+ };++ const crawler = await makeOneshotCrawler({ requestHandler, renderingTypePredictor }, [+ `http://${HOSTNAME}:${port}/static`,+ ]);++ await crawler.run();++ expect(renderingTypePredictor.predict).toHaveBeenCalledOnce();+ expect(renderingTypePredictor.initialize).not.toHaveBeenCalled();+ });+ });+test('validates userData against the router schema when adding requests', async () => {const router = createAdaptivePlaywrightRouter({ DETAIL: z.object({ id: z.string() }) });router.addHandler('DETAIL', async () => {});