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.

fix: Fix useState behavior in adaptive crawler (#2941)

Jan Buchar52823818bd66
diff --git a/packages/core/src/crawlers/crawler_commons.ts b/packages/core/src/crawlers/crawler_commons.ts
index fdc7777ac..40187cdbd 100644
--- a/packages/core/src/crawlers/crawler_commons.ts
+++ b/packages/core/src/crawlers/crawler_commons.ts
@@ -291,18 +291,10 @@ export class RequestHandlerResult {
id: this.idOrDefault(idOrName),
name: idOrName,
getValue: async (key) => this.getKeyValueStoreChangedValue(idOrName, key) ?? (await store.getValue(key)),
- getAutoSavedValue: async <T extends Dictionary = Dictionary>(key: string, defaultValue: T = {} as T) => {
- let value = this.getKeyValueStoreChangedValue(idOrName, key);
- if (value === null) {
- value = (await store.getValue(key)) ?? defaultValue;
- this.setKeyValueStoreChangedValue(idOrName, key, value);
- }
-
- return value as T;
- },
setValue: async (key, value, options) => {
this.setKeyValueStoreChangedValue(idOrName, key, value, options);
},
+ getAutoSavedValue: store.getAutoSavedValue.bind(store),
getPublicUrl: store.getPublicUrl.bind(store),
};
};
diff --git a/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts b/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts
index 83d38bb86..d37ae2916 100644
--- a/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts
+++ b/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts
@@ -346,13 +346,11 @@ export class AdaptivePlaywrightCrawler extends PlaywrightCrawler {
crawlingContext.log.debug(`Running browser request handler for ${crawlingContext.request.url}`);
this.stats.trackBrowserRequestHandlerRun();
- // Keep a copy of the `useState` value, we need to use the old state when trying the HTTP handler to have
- // the same outcome. We don't need to care about its persistence, since we only run this for detection
- // purposes. We read the value directly instead of using `useState` so there are no side effects.
- const kvs = await crawlingContext.getKeyValueStore();
- const oldState = await kvs.getValue(AdaptivePlaywrightCrawler.CRAWLEE_STATE_KEY);
- const oldStateCopy = JSON.parse(JSON.stringify(oldState));
- const browserRun = await this.runRequestHandlerInBrowser(crawlingContext);
+ // Run the request handler in a browser. The copy of the crawler state is kept so that we can perform
+ // a rendering type detection if necessary. Without this measure, the HTTP request handler would run
+ // under different conditions, which could change its behavior. Changes done to the crawler state by
+ // the HTTP request handler will not be committed to the actual storage.
+ const { result: browserRun, initialStateCopy } = await this.runRequestHandlerInBrowser(crawlingContext);
if (!browserRun.ok) {
throw browserRun.error;
@@ -362,7 +360,7 @@ export class AdaptivePlaywrightCrawler extends PlaywrightCrawler {
if (shouldDetectRenderingType) {
crawlingContext.log.debug(`Detecting rendering type for ${crawlingContext.request.url}`);
- const plainHTTPRun = await this.runRequestHandlerWithPlainHTTP(crawlingContext, oldStateCopy);
+ const plainHTTPRun = await this.runRequestHandlerWithPlainHTTP(crawlingContext, initialStateCopy);
const detectionResult: RenderingType = (() => {
if (!plainHTTPRun.ok) {
@@ -412,8 +410,9 @@ export class AdaptivePlaywrightCrawler extends PlaywrightCrawler {
protected async runRequestHandlerInBrowser(
crawlingContext: PlaywrightCrawlingContext,
- ): Promise<Result<RequestHandlerResult>> {
+ ): Promise<{ result: Result<RequestHandlerResult>; initialStateCopy?: Record<string, unknown> }> {
const result = new RequestHandlerResult(this.config, AdaptivePlaywrightCrawler.CRAWLEE_STATE_KEY);
+ let initialStateCopy: Record<string, unknown> | undefined;
try {
await super._runRequestHandler.call(
@@ -483,7 +482,13 @@ export class AdaptivePlaywrightCrawler extends PlaywrightCrawler {
},
addRequests: result.addRequests,
pushData: result.pushData,
- useState: this.allowStorageAccess(result.useState),
+ useState: this.allowStorageAccess(async (defaultValue) => {
+ const state = await result.useState(defaultValue);
+ if (initialStateCopy === undefined) {
+ initialStateCopy = JSON.parse(JSON.stringify(state));
+ }
+ return state;
+ }),
getKeyValueStore: this.allowStorageAccess(result.getKeyValueStore),
}),
);
@@ -493,9 +498,9 @@ export class AdaptivePlaywrightCrawler extends PlaywrightCrawler {
}),
crawlingContext,
);
- return { result, ok: true };
+ return { result: { result, ok: true }, initialStateCopy };
} catch (error) {
- return { error, ok: false };
+ return { result: { error, ok: false }, initialStateCopy };
}
}
diff --git a/test/core/crawlers/adaptive_playwright_crawler.test.ts b/test/core/crawlers/adaptive_playwright_crawler.test.ts
index 3aef3d8ec..93b700469 100644
--- a/test/core/crawlers/adaptive_playwright_crawler.test.ts
+++ b/test/core/crawlers/adaptive_playwright_crawler.test.ts
@@ -274,6 +274,46 @@ describe('AdaptivePlaywrightCrawler', () => {
expect(state!.value).toEqual({ count: 3 });
});
+ test('should return deeply equal but not identical state objects across handler runs', async () => {
+ // Force detection to happen
+ const renderingTypePredictor = makeRiggedRenderingTypePredictor({
+ detectionProbabilityRecommendation: 1,
+ renderingType: 'clientOnly',
+ });
+
+ // We'll store state references to compare them later
+ const stateReferences: any[] = [];
+
+ const requestHandler: AdaptivePlaywrightCrawlerOptions['requestHandler'] = vi.fn(async ({ useState }) => {
+ const state = await useState({ data: { nested: { value: 42 } } });
+ stateReferences.push(JSON.parse(JSON.stringify(state)));
+ state.randomNumber = Math.random();
+ });
+
+ // Run the crawler
+ const crawler = await makeOneshotCrawler(
+ {
+ requestHandler,
+ renderingTypePredictor,
+ },
+ [`http://${HOSTNAME}:${port}/static`],
+ );
+
+ await crawler.run();
+
+ // The request handler should have run twice (once in browser, once in HTTP-only mode for detection)
+ expect(requestHandler).toHaveBeenCalledTimes(2);
+ expect(stateReferences).toHaveLength(2);
+
+ // The state objects should be deeply equal (same values)
+ expect(stateReferences[0]).toEqual(stateReferences[1]);
+
+ // But they should not be the same object instance (different references)
+ // This is important to ensure that state objects are properly cloned between handler runs
+ // and that modifications to one state object don't affect others
+ expect(stateReferences[0]).not.toBe(stateReferences[1]);
+ });
+
test('should persist key-value store changes', async () => {
const renderingTypePredictor = makeRiggedRenderingTypePredictor({
detectionProbabilityRecommendation: 0,