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
fix(adaptive-crawler): Fix persistence of rendering type detection results (#3368)
Jan Buchar4abca8bacf06
diff --git a/packages/playwright-crawler/src/internals/utils/rendering-type-prediction.ts b/packages/playwright-crawler/src/internals/utils/rendering-type-prediction.tsindex 29c342ede..e325d6f74 100644--- a/packages/playwright-crawler/src/internals/utils/rendering-type-prediction.ts+++ b/packages/playwright-crawler/src/internals/utils/rendering-type-prediction.ts@@ -43,16 +43,45 @@ export interface RenderingTypePredictorOptions {* @experimental*/export class RenderingTypePredictor {- private renderingTypeDetectionResults = new Map<RenderingType, Map<string | undefined, URLComponents[]>>();private detectionRatio: number;- private state: RecoverableState<{ logreg: LogisticRegression }>;+ private state: RecoverableState<{+ logreg: LogisticRegression;+ detectionResults: Map<RenderingType, Map<string | undefined, URLComponents[]>>;+ }>;constructor({ detectionRatio, persistenceOptions }: RenderingTypePredictorOptions) {this.detectionRatio = detectionRatio;this.state = new RecoverableState({- defaultState: { logreg: new LogisticRegression({ numSteps: 1000, learningRate: 0.05 }) },- serialize: (state) => JSON.stringify({ logreg: state.logreg.toJSON() }),- deserialize: (serializedState) => ({ logreg: LogisticRegression.load(JSON.parse(serializedState).logreg) }),+ defaultState: {+ logreg: new LogisticRegression({ numSteps: 1000, learningRate: 0.05 }),+ detectionResults: new Map<RenderingType, Map<string | undefined, URLComponents[]>>(),+ },+ serialize: (state) =>+ JSON.stringify({+ logreg: state.logreg.toJSON(),+ detectionResults: Array.from(state.detectionResults.entries()).map(+ ([renderingType, urlPartsByLabel]) => ({+ renderingType,+ urlPartsByLabel: Array.from(urlPartsByLabel.entries()).map(([label, urlParts]) => ({+ label,+ urlParts,+ })),+ }),+ ),+ }),+ deserialize: (serializedState) => {+ const { logreg, detectionResults = [] } = JSON.parse(serializedState);++ return {+ logreg: LogisticRegression.load(logreg),+ detectionResults: new Map(+ detectionResults.map((serializedItem: any) => [+ serializedItem.renderingType,+ new Map(serializedItem.urlPartsByLabel.map((item: any) => [item.label, item.urlParts])),+ ]),+ ),+ };+ },persistStateKey: 'rendering-type-predictor-state',persistenceEnabled: true,...persistenceOptions,@@ -96,23 +125,28 @@ export class RenderingTypePredictor {/*** Store the rendering type for a given URL and request label. This updates the underlying prediction model, which may be costly.*/- public storeResult({ url, loadedUrl, label }: Request, renderingType: RenderingType) {- const resultUrl = new URL(loadedUrl ?? url);+ public storeResult(requests: Request | Request[], renderingType: RenderingType) {+ const state = this.state.currentValue;- if (!this.renderingTypeDetectionResults.has(renderingType)) {- this.renderingTypeDetectionResults.set(renderingType, new Map());- }+ for (const { url, loadedUrl, label } of Array.isArray(requests) ? requests : [requests]) {+ const resultUrl = new URL(loadedUrl ?? url);++ if (!state.detectionResults.has(renderingType)) {+ state.detectionResults.set(renderingType, new Map());+ }++ if (!state.detectionResults.get(renderingType)!.has(label)) {+ state.detectionResults.get(renderingType)!.set(label, []);+ }- if (!this.renderingTypeDetectionResults.get(renderingType)!.has(label)) {- this.renderingTypeDetectionResults.get(renderingType)!.set(label, []);+ state.detectionResults.get(renderingType)!.get(label)!.push(urlComponents(resultUrl));}- this.renderingTypeDetectionResults.get(renderingType)!.get(label)!.push(urlComponents(resultUrl));this.retrain();}private resultCount(label: string | undefined): number {- return Array.from(this.renderingTypeDetectionResults.values())+ return Array.from(this.state.currentValue.detectionResults.values()).map((results) => results.get(label)?.length ?? 0).reduce((acc, value) => acc + value, 0);}@@ -120,12 +154,12 @@ export class RenderingTypePredictor {protected calculateFeatureVector(url: URLComponents, label: string | undefined): FeatureVector {return [mean(- (this.renderingTypeDetectionResults.get('static')?.get(label) ?? []).map(+ (this.state.currentValue.detectionResults.get('static')?.get(label) ?? []).map((otherUrl) => calculateUrlSimilarity(url, otherUrl) ?? 0,),) ?? 0,mean(- (this.renderingTypeDetectionResults.get('clientOnly')?.get(label) ?? []).map(+ (this.state.currentValue.detectionResults.get('clientOnly')?.get(label) ?? []).map((otherUrl) => calculateUrlSimilarity(url, otherUrl) ?? 0,),) ?? 0,@@ -139,7 +173,7 @@ export class RenderingTypePredictor {];const Y: number[] = [0, 1];- for (const [renderingType, urlsByLabel] of this.renderingTypeDetectionResults.entries()) {+ for (const [renderingType, urlsByLabel] of this.state.currentValue.detectionResults.entries()) {for (const [label, urls] of urlsByLabel) {for (const url of urls) {X.push(this.calculateFeatureVector(url, label));diff --git a/test/core/crawlers/rendering_type_predictor.test.ts b/test/core/crawlers/rendering_type_predictor.test.tsnew file mode 100644index 000000000..de4df27ec--- /dev/null+++ b/test/core/crawlers/rendering_type_predictor.test.ts@@ -0,0 +1,76 @@+import { Request } from '@crawlee/core';+import { RenderingTypePredictor } from '@crawlee/playwright';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { MemoryStorageEmulator } from '../../shared/MemoryStorageEmulator';++describe('RenderingTypePredictor', () => {+ const localStorageEmulator = new MemoryStorageEmulator();++ beforeEach(async () => {+ await localStorageEmulator.init();+ });++ afterEach(async () => {+ await localStorageEmulator.destroy();+ });++ describe('persistence', () => {+ it('should persist and restore state correctly', async () => {+ const persistStateKey = 'rendering-type-predictor-test';++ // Create a predictor and store some results+ const predictor = new RenderingTypePredictor({+ detectionRatio: 0.1,+ persistenceOptions: { persistStateKey },+ });+ await predictor.initialize();++ // Store some detection results+ const staticRequest = new Request({ url: 'https://example.com/static-page' });+ const clientRequest = new Request({ url: 'https://example.com/dynamic-app' });++ predictor.storeResult(staticRequest, 'static');+ predictor.storeResult(clientRequest, 'clientOnly');++ // Persist the state+ const store = localStorageEmulator.getKeyValueStore();+ // eslint-disable-next-line dot-notation+ await predictor['state'].persistState(); // Access private state for persistence++ // Verify state was persisted+ const persistedRecord = await store.getRecord(persistStateKey);+ expect(persistedRecord).not.toBeNull();+ expect(persistedRecord?.value).toBeDefined();++ const parsedState = JSON.parse(persistedRecord!.value as string);+ expect(parsedState).toHaveProperty('logreg');+ expect(parsedState).toHaveProperty('detectionResults');++ // Create a new predictor and verify it restores the state+ const restoredPredictor = new RenderingTypePredictor({+ detectionRatio: 0.1,+ persistenceOptions: { persistStateKey },+ });+ await restoredPredictor.initialize();++ // The restored predictor should predict 'static' for a similar URL+ const prediction = restoredPredictor.predict(new Request({ url: 'https://example.com/static-page' }));+ expect(prediction.renderingType).toBe('static');+ });++ it('should initialize with default state when no persisted state exists', async () => {+ const predictor = new RenderingTypePredictor({+ detectionRatio: 0.5,+ persistenceOptions: { persistStateKey: 'non-existent-key' },+ });++ await expect(predictor.initialize()).resolves.not.toThrow();++ // With no stored results, prediction should return clientOnly with high detection probability+ const prediction = predictor.predict(new Request({ url: 'https://example.com/test' }));+ expect(prediction.renderingType).toBe('clientOnly');+ expect(prediction.detectionProbabilityRecommendation).toBe(1);+ });+ });+});