@crawlee/playwright 4.0.0-rc.1 → 4.0.0-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -27,33 +27,6 @@ export function playwrightBrowserPool(options = {}) {
27
27
  const { launchContext, headless, configuration, ...poolOptions } = options;
28
28
  return playwrightLauncher(launchContext, headless, configuration).createBrowserPool(poolOptions);
29
29
  }
30
- /**
31
- * The {@link RemoteBrowserPool} counterpart of {@link playwrightBrowserPool}: connects to a remote browser
32
- * service (Browserbase, Browserless, Steel, ...) with a Playwright plugin derived from `launchContext`.
33
- *
34
- * A {@link PlaywrightCrawler} accepts the same connection details directly via
35
- * {@link BrowserCrawlerOptions.remoteBrowser|`remoteBrowser`}; reach for this factory when you also need to
36
- * tune the wrapping pool, or to share one remote pool between crawlers.
37
- *
38
- * **Example usage:**
39
- *
40
- * ```javascript
41
- * const crawler = new PlaywrightCrawler({
42
- * browserPool: remotePlaywrightBrowserPool({
43
- * endpoint: 'wss://production-sfo.browserless.io?token=xxx',
44
- * maxOpenBrowsers: 2,
45
- * browserPoolOptions: { useFingerprints: false },
46
- * }),
47
- * requestHandler: async ({ page }) => { ... },
48
- * });
49
- * ```
50
- *
51
- * @category Browser management
52
- */
53
- export function remotePlaywrightBrowserPool(options) {
54
- const { launchContext, headless, configuration, ...remoteOptions } = options;
55
- return playwrightLauncher(launchContext, headless, configuration).createRemoteBrowserPool(remoteOptions);
56
- }
57
30
  function playwrightLauncher(launchContext = {}, headless, configuration) {
58
31
  return new PlaywrightLauncher(headless == null
59
32
  ? launchContext
@@ -4,6 +4,7 @@ import type { Dictionary } from '@crawlee/types';
4
4
  // @ts-ignore optional peer dependency or compatibility with es2022
5
5
  import type { Page, Response } from 'playwright';
6
6
  import { z } from 'zod';
7
+ import { type PlaywrightRemoteBrowserOptions } from './playwright-browser-pool.js';
7
8
  import type { PlaywrightLaunchContext } from './playwright-launcher.js';
8
9
  import type { DirectNavigationOptions, HandleCloudflareChallengeOptions, PlaywrightContextUtils } from './utils/playwright-utils.js';
9
10
  export type PlaywrightGotoOptions = NonNullable<Parameters<Page['goto']>[1]>;
@@ -20,6 +21,8 @@ export interface PlaywrightCrawlerOptions<ContextExtension = Dictionary<never>,
20
21
  * Can be also set via {@link Configuration}.
21
22
  */
22
23
  headless?: boolean;
24
+ /** See {@link BrowserCrawlerOptions.remoteBrowser}; Playwright additionally lets you pick the `protocol`. */
25
+ remoteBrowser?: PlaywrightRemoteBrowserOptions;
23
26
  /**
24
27
  * Async functions that are sequentially evaluated before the navigation. Good for setting additional cookies
25
28
  * or browser properties before navigation. The function receives the `crawlingContext`; the options object
@@ -161,8 +164,6 @@ export declare class PlaywrightCrawler<ContextExtension = Dictionary<never>, Ext
161
164
  // @ts-ignore optional peer dependency or compatibility with es2022
162
165
  configuration: z.ZodOptional<z.ZodInstanceOf<import("@crawlee/browser").Configuration>>;
163
166
  storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
164
- // @ts-ignore optional peer dependency or compatibility with es2022
165
- eventManager: z.ZodOptional<z.ZodInstanceOf<import("@crawlee/browser").EventManager>>;
166
167
  logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
167
168
  minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
168
169
  maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
@@ -221,8 +222,6 @@ export declare class PlaywrightCrawler<ContextExtension = Dictionary<never>, Ext
221
222
  // @ts-ignore optional peer dependency or compatibility with es2022
222
223
  configuration: z.ZodOptional<z.ZodInstanceOf<import("@crawlee/browser").Configuration>>;
223
224
  storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
224
- // @ts-ignore optional peer dependency or compatibility with es2022
225
- eventManager: z.ZodOptional<z.ZodInstanceOf<import("@crawlee/browser").EventManager>>;
226
225
  logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
227
226
  minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
228
227
  maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
@@ -254,6 +253,11 @@ export declare class PlaywrightCrawler<ContextExtension = Dictionary<never>, Ext
254
253
  * Returns a `postNavigationHooks`-ready hook that runs {@link PlaywrightContextUtils.handleCloudflareChallenge}
255
254
  * and propagates the post-challenge {@link Response} back into the crawling context via its return value.
256
255
  *
256
+ * Cloudflare serves its challenge pages with a 403 status, which is part of the default `blockedStatusCodes`.
257
+ * Keep it there - the hook runs before the blocked-status check and replaces the response on a solved
258
+ * challenge, so solved requests pass it, while unsolved or undetected challenges keep the 403 and get
259
+ * retried with a fresh session.
260
+ *
257
261
  * **Example usage**
258
262
  * ```ts
259
263
  * import { PlaywrightCrawler, handleCloudflareChallengeHook } from 'crawlee';
@@ -1,7 +1,8 @@
1
- import { BrowserCrawler, RequestState, Router, serviceLocator } from '@crawlee/browser';
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+ import { BrowserCrawler, DownloadStartedError, RequestState, Router, serviceLocator } from '@crawlee/browser';
2
3
  import { assertBrowserPoolNotConfigured, parseArgument, schemas } from '@crawlee/utils/internal';
3
4
  import { z } from 'zod';
4
- import { playwrightBrowserPool, remotePlaywrightBrowserPool } from './playwright-browser-pool.js';
5
+ import { playwrightBrowserPool } from './playwright-browser-pool.js';
5
6
  import { blockRequests, compileScript, enqueueLinksByClickingElements, gotoExtended, handleCloudflareChallenge, infiniteScroll, injectFile, injectJQuery, parseWithCheerio, saveSnapshot, } from './utils/playwright-utils.js';
6
7
  /**
7
8
  * Provides a simple framework for parallel crawling of web pages
@@ -99,9 +100,7 @@ export class PlaywrightCrawler extends BrowserCrawler {
99
100
  super({
100
101
  ...browserCrawlerOptions,
101
102
  configuration,
102
- browserPoolBuilder: (remoteBrowser) => remoteBrowser
103
- ? remotePlaywrightBrowserPool({ ...remoteBrowser, launchContext, headless, configuration })
104
- : playwrightBrowserPool({ launchContext, headless, configuration }),
103
+ browserPoolBuilder: (remoteBrowser) => playwrightBrowserPool({ launchContext, headless, configuration, remoteBrowser }),
105
104
  contextPipelineBuilder: () => this.#buildContextPipeline(),
106
105
  });
107
106
  }
@@ -109,13 +108,46 @@ export class PlaywrightCrawler extends BrowserCrawler {
109
108
  return this.buildContextPipeline().compose(this.#enhanceContext.bind(this));
110
109
  }
111
110
  async navigationHandler(crawlingContext, gotoOptions) {
112
- return gotoExtended(crawlingContext.page, crawlingContext.request, gotoOptions);
111
+ const { page } = crawlingContext;
112
+ const { promise: downloadStarted, resolve } = Promise.withResolvers();
113
+ const onDownload = () => resolve();
114
+ page.once('download', onDownload);
115
+ try {
116
+ return await gotoExtended(page, crawlingContext.request, gotoOptions);
117
+ }
118
+ catch (error) {
119
+ // `goto` can reject before the `download` event arrives, and `listDownloads()` would miss it.
120
+ // ponytail: fixed 5 s bound, tie it to the navigation window if downloads start slower than that
121
+ if (error.message?.includes('Download is starting')) {
122
+ await Promise.race([downloadStarted, delay(5_000, undefined, { ref: false })]);
123
+ throw new DownloadStartedError(error.message, { cause: error });
124
+ }
125
+ throw error;
126
+ }
127
+ finally {
128
+ page.off('download', onDownload);
129
+ }
113
130
  }
114
131
  async #enhanceContext(context) {
115
132
  const waitForSelector = async (selector, timeoutMs = 5_000) => {
116
133
  const locator = context.page.locator(selector).first();
117
134
  await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
118
135
  };
136
+ const parseWithCheerioFn = async (selector, timeoutMs = 5_000) => {
137
+ if (selector) {
138
+ await waitForSelector(selector, timeoutMs);
139
+ }
140
+ return parseWithCheerio(context.page, this.ignoreShadowRoots, this.ignoreIframes);
141
+ };
142
+ const querySelectorAll = async (selector, timeoutMs) => {
143
+ const matches = (await parseWithCheerioFn(selector, timeoutMs))(selector);
144
+ // The browser located it but the Cheerio snapshot does not have it - a Playwright-only selector,
145
+ // or an element under a shadow root/iframe the snapshot was told to ignore.
146
+ if (matches.length === 0) {
147
+ throw new Error(`Selector '${selector}' not found in the page snapshot.`);
148
+ }
149
+ return matches;
150
+ };
119
151
  const downloads = [];
120
152
  context.page.on('download', (download) => downloads.push(download));
121
153
  return {
@@ -130,12 +162,9 @@ export class PlaywrightCrawler extends BrowserCrawler {
130
162
  },
131
163
  blockRequests: async (options) => blockRequests(context.page, options),
132
164
  waitForSelector,
133
- parseWithCheerio: async (selector, timeoutMs = 5_000) => {
134
- if (selector) {
135
- await waitForSelector(selector, timeoutMs);
136
- }
137
- return parseWithCheerio(context.page, this.ignoreShadowRoots, this.ignoreIframes);
138
- },
165
+ parseWithCheerio: parseWithCheerioFn,
166
+ querySelectorAll,
167
+ querySelectorOne: async (selector, timeoutMs) => (await querySelectorAll(selector, timeoutMs)).first(),
139
168
  infiniteScroll: async (options) => infiniteScroll(context.page, options),
140
169
  listDownloads: async () => downloads,
141
170
  saveSnapshot: async (options) => saveSnapshot(context.page, {
@@ -149,7 +178,14 @@ export class PlaywrightCrawler extends BrowserCrawler {
149
178
  }),
150
179
  compileScript: (scriptString, ctx) => compileScript(scriptString, ctx),
151
180
  handleCloudflareChallenge: async (options) => {
152
- return handleCloudflareChallenge(context.page, context.request.url, options);
181
+ let response;
182
+ try {
183
+ response = context.response;
184
+ }
185
+ catch {
186
+ // the getter throws before navigation, with `skipNavigation`, and when navigation produced no response
187
+ }
188
+ return handleCloudflareChallenge(context.page, context.request.url, options, response);
153
189
  },
154
190
  };
155
191
  }
@@ -158,6 +194,11 @@ export class PlaywrightCrawler extends BrowserCrawler {
158
194
  * Returns a `postNavigationHooks`-ready hook that runs {@link PlaywrightContextUtils.handleCloudflareChallenge}
159
195
  * and propagates the post-challenge {@link Response} back into the crawling context via its return value.
160
196
  *
197
+ * Cloudflare serves its challenge pages with a 403 status, which is part of the default `blockedStatusCodes`.
198
+ * Keep it there - the hook runs before the blocked-status check and replaces the response on a solved
199
+ * challenge, so solved requests pass it, while unsolved or undetected challenges keep the 403 and get
200
+ * retried with a fresh session.
201
+ *
161
202
  * **Example usage**
162
203
  * ```ts
163
204
  * import { PlaywrightCrawler, handleCloudflareChallengeHook } from 'crawlee';
@@ -1,5 +1,5 @@
1
1
  import { BrowserLauncher, Configuration } from '@crawlee/browser';
2
- import { PlaywrightPlugin } from '@crawlee/browser-pool';
2
+ import { PlaywrightPlugin, RemotePlaywrightPlugin } from '@crawlee/browser-pool';
3
3
  import { parseArgument, schemas } from '@crawlee/utils/internal';
4
4
  import { z } from 'zod';
5
5
  /**
@@ -35,6 +35,7 @@ export class PlaywrightLauncher extends BrowserLauncher {
35
35
  }, configuration);
36
36
  this.configuration = configuration;
37
37
  this.Plugin = PlaywrightPlugin;
38
+ this.RemotePlugin = RemotePlaywrightPlugin;
38
39
  }
39
40
  }
40
41
  /**
@@ -19,7 +19,8 @@
19
19
  */
20
20
  import { Configuration, type Request } from '@crawlee/browser';
21
21
  import type { BatchAddRequestsResult, Dictionary } from '@crawlee/types';
22
- import type { CheerioAPI } from 'cheerio';
22
+ import type { Cheerio, CheerioAPI } from 'cheerio';
23
+ import type { AnyNode } from 'domhandler';
23
24
  // @ts-ignore optional peer dependency or compatibility with es2022
24
25
  import type { Download, Page, Response } from 'playwright';
25
26
  import type { EnqueueLinksByClickingElementsOptions } from '../enqueue-links/click-elements.js';
@@ -318,22 +319,29 @@ export interface HandleCloudflareChallengeOptions {
318
319
  *
319
320
  * On a successfully solved challenge the page is reloaded and the new {@link Response} is returned, so
320
321
  * it can be propagated back to the crawling context via a hook return value (see
321
- * {@link handleCloudflareChallengeHook}).
322
+ * {@link handleCloudflareChallengeHook}). Thanks to that, the 403 status of the challenge page does not
323
+ * need to be removed from `blockedStatusCodes` - a solved challenge replaces the response before the
324
+ * blocked-status check runs, and an unsolved one is retried with a fresh session.
322
325
  *
323
326
  * Works best with camoufox.
324
327
  *
325
328
  * **Example usage**
326
329
  * ```ts
327
330
  * postNavigationHooks: [
328
- * async (context) => ({ response: await context.handleCloudflareChallenge() }),
331
+ * async (context) => {
332
+ * const response = await context.handleCloudflareChallenge();
333
+ * // `{ response: undefined }` would replace the navigation response and skip the blocked-status check
334
+ * return response && { response };
335
+ * },
329
336
  * ],
330
337
  * ```
331
338
  *
332
339
  * @param page Playwright [`Page`](https://playwright.dev/docs/api/class-page) object
333
340
  * @param url current URL for request identification, only used for logging
334
341
  * @param [options]
342
+ * @param [response] navigation response, used to poll for late-rendered challenge markup when it signals a likely challenge
335
343
  */
336
- export declare function handleCloudflareChallenge(page: Page, url: string, options?: HandleCloudflareChallengeOptions): Promise<Response | undefined>;
344
+ export declare function handleCloudflareChallenge(page: Page, url: string, options?: HandleCloudflareChallengeOptions, response?: Response): Promise<Response | undefined>;
337
345
  export interface PlaywrightContextUtils {
338
346
  /**
339
347
  * Injects a JavaScript file into current `page`.
@@ -420,6 +428,15 @@ export interface PlaywrightContextUtils {
420
428
  * ```
421
429
  */
422
430
  waitForSelector(selector: string, timeoutMs?: number): Promise<void>;
431
+ /**
432
+ * Like {@link PlaywrightContextUtils.waitForSelector|`waitForSelector`}, but returns the matched elements
433
+ * as a Cheerio object. Throws when nothing matches.
434
+ */
435
+ querySelectorAll(selector: string, timeoutMs?: number): Promise<Cheerio<AnyNode>>;
436
+ /**
437
+ * Like {@link PlaywrightContextUtils.querySelectorAll|`querySelectorAll`}, but returns only the first match.
438
+ */
439
+ querySelectorOne(selector: string, timeoutMs?: number): Promise<Cheerio<AnyNode>>;
423
440
  /**
424
441
  * Returns Cheerio handle for `page.content()`, allowing to work with the data same way as with {@link CheerioCrawler}.
425
442
  * When provided with the `selector` argument, it waits for it to be available first.
@@ -525,7 +542,11 @@ export interface PlaywrightContextUtils {
525
542
  * **Example usage**
526
543
  * ```ts
527
544
  * postNavigationHooks: [
528
- * async (context) => ({ response: await context.handleCloudflareChallenge() }),
545
+ * async (context) => {
546
+ * const response = await context.handleCloudflareChallenge();
547
+ * // `{ response: undefined }` would replace the navigation response and skip the blocked-status check
548
+ * return response && { response };
549
+ * },
529
550
  * ],
530
551
  * ```
531
552
  *
@@ -22,7 +22,7 @@ import { createRequire } from 'node:module';
22
22
  import vm from 'node:vm';
23
23
  import { Configuration, KeyValueStore, serviceLocator, SessionError, validators } from '@crawlee/browser';
24
24
  import { sleep } from '@crawlee/utils';
25
- import { expandShadowRoots, parseArgument, schemas } from '@crawlee/utils/internal';
25
+ import { expandShadowRoots, parseArgument, schemas, snapshotPageWithIframes } from '@crawlee/utils/internal';
26
26
  import { z } from 'zod';
27
27
  import { LruCache } from '@apify/datastructures';
28
28
  import { enqueueLinksByClickingElements } from '../enqueue-links/click-elements.js';
@@ -400,35 +400,27 @@ export async function saveSnapshot(page, options = {}) {
400
400
  */
401
401
  export async function parseWithCheerio(page, ignoreShadowRoots = false, ignoreIframes = false) {
402
402
  parseArgument(page, validators.browserPage);
403
- const html = ignoreShadowRoots
404
- ? null
405
- : (await page.evaluate(`(${expandShadowRoots.toString()})(document)`));
406
- const pageContent = html || (await page.content());
403
+ const snapshot = await page.evaluateHandle(`(${snapshotPageWithIframes.toString()})(document, ${ignoreShadowRoots ? 'null' : expandShadowRoots.toString()})`);
404
+ const pageContent = (await (await snapshot.getProperty('html')).jsonValue());
407
405
  // Full cheerio (parse5) import for browser compliant parser
408
406
  const { load } = await import('cheerio');
409
407
  const $ = load(pageContent);
410
408
  if (page.frames().length > 1 && !ignoreIframes) {
411
- const frames = await page.$$('iframe');
412
- const cheerioIframes = $('iframe').toArray();
413
- if (frames.length !== cheerioIframes.length) {
414
- serviceLocator
415
- .getLogger()
416
- .warning(`parseWithCheerio: iframe count mismatch between live DOM (${frames.length}) and page snapshot (${cheerioIframes.length}). Some iframes may not be expanded.`);
417
- }
418
- await Promise.all(frames.map(async (frame, index) => {
409
+ const iframes = await (await snapshot.getProperty('iframes')).getProperties();
410
+ await Promise.all([...iframes].map(async ([id, handle]) => {
419
411
  try {
420
- const iframe = await frame.contentFrame();
421
- if (iframe && cheerioIframes[index]) {
412
+ const iframe = await handle.asElement()?.contentFrame();
413
+ if (iframe) {
422
414
  const getIframeHTML = async () => {
423
415
  try {
424
- return iframe.locator('body').first().innerHTML();
416
+ return await iframe.locator('body').first().innerHTML();
425
417
  }
426
418
  catch {
427
419
  return iframe.content();
428
420
  }
429
421
  };
430
422
  const contents = await getIframeHTML();
431
- $(cheerioIframes[index]).replaceWith(`<div class="crawlee-iframe-replacement">${contents}</div>`);
423
+ $(`iframe[data-crawlee-iframe-id="${id}"]`).replaceWith(`<div class="crawlee-iframe-replacement">${contents}</div>`);
432
424
  }
433
425
  }
434
426
  catch (error) {
@@ -436,6 +428,8 @@ export async function parseWithCheerio(page, ignoreShadowRoots = false, ignoreIf
436
428
  }
437
429
  }));
438
430
  }
431
+ await snapshot.dispose();
432
+ $('[data-crawlee-iframe-id]').removeAttr('data-crawlee-iframe-id');
439
433
  return $;
440
434
  }
441
435
  /**
@@ -447,50 +441,74 @@ export async function parseWithCheerio(page, ignoreShadowRoots = false, ignoreIf
447
441
  *
448
442
  * On a successfully solved challenge the page is reloaded and the new {@link Response} is returned, so
449
443
  * it can be propagated back to the crawling context via a hook return value (see
450
- * {@link handleCloudflareChallengeHook}).
444
+ * {@link handleCloudflareChallengeHook}). Thanks to that, the 403 status of the challenge page does not
445
+ * need to be removed from `blockedStatusCodes` - a solved challenge replaces the response before the
446
+ * blocked-status check runs, and an unsolved one is retried with a fresh session.
451
447
  *
452
448
  * Works best with camoufox.
453
449
  *
454
450
  * **Example usage**
455
451
  * ```ts
456
452
  * postNavigationHooks: [
457
- * async (context) => ({ response: await context.handleCloudflareChallenge() }),
453
+ * async (context) => {
454
+ * const response = await context.handleCloudflareChallenge();
455
+ * // `{ response: undefined }` would replace the navigation response and skip the blocked-status check
456
+ * return response && { response };
457
+ * },
458
458
  * ],
459
459
  * ```
460
460
  *
461
461
  * @param page Playwright [`Page`](https://playwright.dev/docs/api/class-page) object
462
462
  * @param url current URL for request identification, only used for logging
463
463
  * @param [options]
464
+ * @param [response] navigation response, used to poll for late-rendered challenge markup when it signals a likely challenge
464
465
  */
465
- export async function handleCloudflareChallenge(page, url, options = {}) {
466
- options.isBlockedCallback ??= async () => {
467
- const isBlocked = await page.evaluate(() => {
468
- return document.querySelector('h1')?.textContent?.trim().includes('Sorry, you have been blocked');
466
+ export async function handleCloudflareChallenge(page, url, options = {}, response) {
467
+ // The options object may outlive this call (the pre-wrapped hook reuses one instance for all
468
+ // requests and retries), so the defaults are kept local instead of being memoized on `options` -
469
+ // memoizing them would pin the closed-over `page` of the first call forever.
470
+ const isBlockedCallback = options.isBlockedCallback ??
471
+ (async (p) => {
472
+ const isBlocked = await p.evaluate(() => {
473
+ return document.querySelector('h1')?.textContent?.trim().includes('Sorry, you have been blocked');
474
+ });
475
+ return !!isBlocked;
469
476
  });
470
- return !!isBlocked;
471
- };
472
- options.isChallengeCallback ??= async () => {
473
- return await page.evaluate(async () => {
474
- // Cloudflare keeps reshuffling the wrapper elements between `.footer-inner` and `.ray-id`,
475
- // so only the stable outer classes are matched.
476
- return !!document.querySelector('.footer .footer-inner .ray-id');
477
+ const isChallengeCallback = options.isChallengeCallback ??
478
+ (async (p) => {
479
+ return await p.evaluate(async () => {
480
+ // Cloudflare keeps reshuffling the wrapper elements between `.footer-inner` and `.ray-id`,
481
+ // so only the stable outer classes are matched.
482
+ return !!document.querySelector('.footer .footer-inner .ray-id');
483
+ });
477
484
  });
478
- };
479
485
  const retryBlocked = async () => {
480
- const isBlocked = await options.isBlockedCallback(page).catch(() => false);
486
+ const isBlocked = await isBlockedCallback(page).catch(() => false);
481
487
  if (isBlocked) {
482
488
  throw new SessionError(`Blocked by Cloudflare when processing ${url}`);
483
489
  }
484
490
  };
485
491
  // check if we ended up on the CF challenge page
486
492
  const isChallenge = async () => {
487
- return options.isChallengeCallback(page).catch(async () => {
493
+ return isChallengeCallback(page).catch(async () => {
488
494
  // the challenge page navigates itself, which destroys the context of an in-flight check
489
495
  await page.waitForLoadState('domcontentloaded').catch(() => { });
490
- return options.isChallengeCallback(page).catch(() => false);
496
+ return isChallengeCallback(page).catch(() => false);
491
497
  });
492
498
  };
493
- if (!(await isChallenge())) {
499
+ // The challenge markup can finish rendering only after the `load` event, so when the response signals
500
+ // a likely challenge, poll for it instead of checking once. A 403 alone is not enough - it must come
501
+ // from Cloudflare (the `cf-ray` header), so 403s served by other stacks keep failing fast.
502
+ const headers = response?.headers() ?? {};
503
+ const likelyChallenge = headers['cf-mitigated'] === 'challenge' || (response?.status() === 403 && 'cf-ray' in headers);
504
+ let detected = await isChallenge();
505
+ for (let i = 0; !detected && likelyChallenge && i < 10; i++) {
506
+ // a hard-blocked page never turns into a challenge, so fail fast instead of finishing the poll
507
+ await retryBlocked();
508
+ await sleep(500);
509
+ detected = await isChallenge();
510
+ }
511
+ if (!detected) {
494
512
  await retryBlocked();
495
513
  return undefined;
496
514
  }
@@ -4,13 +4,17 @@ export type RenderingType = 'clientOnly' | 'static';
4
4
  export interface RenderingTypePredictorOptions {
5
5
  /** A number between 0 and 1 that determines the desired ratio of rendering type detections */
6
6
  detectionRatio: number;
7
+ /**
8
+ * Unique identifier for this predictor instance. Used to generate a unique persistence key when
9
+ * `persistenceOptions.persistStateKey` is not provided. If not provided, an auto-incrementing ID is used.
10
+ * Explicit IDs share one namespace with the generated ones, so avoid explicit IDs like `'0'` or `'1'`.
11
+ */
12
+ id?: string | number;
7
13
  persistenceOptions?: Partial<RecoverableStatePersistenceOptions>;
8
14
  }
9
15
  /**
10
16
  * Minimal contract that any object passed to {@link AdaptivePlaywrightCrawler} as its
11
17
  * `renderingTypePredictor` option must satisfy.
12
- *
13
- * @experimental
14
18
  */
15
19
  export interface IRenderingTypePredictor {
16
20
  /**
@@ -24,7 +28,8 @@ export interface IRenderingTypePredictor {
24
28
  detectionProbabilityRecommendation: number;
25
29
  }>;
26
30
  /**
27
- * Report a detected rendering type, so that future predictions can take it into account.
31
+ * Report a rendering type established by a detection, or `clientOnly` when the `resultChecker` rejected an
32
+ * HTTP-only result, so that future predictions can take it into account.
28
33
  *
29
34
  * The crawler does not await this per detection - it collects the returned promises and drains them in
30
35
  * `teardown()`, so an implementation that persists results asynchronously can keep batching its writes
@@ -34,12 +39,12 @@ export interface IRenderingTypePredictor {
34
39
  }
35
40
  /**
36
41
  * 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.
37
- *
38
- * @experimental
39
42
  */
40
43
  export declare class RenderingTypePredictor implements IRenderingTypePredictor {
41
44
  #private;
42
- constructor({ detectionRatio, persistenceOptions }: RenderingTypePredictorOptions);
45
+ /** The identifier used in the default persistence key. */
46
+ readonly id: string;
47
+ constructor({ detectionRatio, id, persistenceOptions }: RenderingTypePredictorOptions);
43
48
  /**
44
49
  * Initialize the predictor by restoring persisted state.
45
50
  */
@@ -62,20 +62,22 @@ const stateCodec = z.codec(persistedState, predictorState, {
62
62
  });
63
63
  /**
64
64
  * 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.
65
- *
66
- * @experimental
67
65
  */
68
66
  export class RenderingTypePredictor {
67
+ static #nextId = 0;
68
+ /** The identifier used in the default persistence key. */
69
+ id;
69
70
  #detectionRatio;
70
71
  #state;
71
- constructor({ detectionRatio, persistenceOptions }) {
72
+ constructor({ detectionRatio, id, persistenceOptions }) {
73
+ this.id = id != null ? String(id) : String(RenderingTypePredictor.#nextId++);
72
74
  this.#detectionRatio = detectionRatio;
73
75
  this.#state = new RecoverableState({
74
76
  defaultState: () => stateCodec.decode({}),
75
77
  // The codec validates in the decode direction, so it is a Standard Schema as-is; encoding needs a call.
76
78
  deserialize: stateCodec,
77
79
  serialize: (state) => stateCodec.encode(state),
78
- persistStateKey: 'rendering-type-predictor-state',
80
+ persistStateKey: `CRAWLEE_RENDERING_TYPE_PREDICTOR_STATE_${this.id}`,
79
81
  persistenceEnabled: true,
80
82
  ...persistenceOptions,
81
83
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crawlee/playwright",
3
- "version": "4.0.0-rc.1",
3
+ "version": "4.0.0-rc.3",
4
4
  "description": "The scalable web crawling and scraping library for JavaScript/Node.js. Enables development of data extraction and web automation jobs (not only) with headless Chrome and Puppeteer.",
5
5
  "engines": {
6
6
  "node": ">=22.13.0"
@@ -48,21 +48,23 @@
48
48
  },
49
49
  "dependencies": {
50
50
  "@apify/datastructures": "^3.0.1",
51
- "@apify/timeout": "^1.0.1",
52
- "@crawlee/basic": "4.0.0-rc.1",
53
- "@crawlee/browser": "4.0.0-rc.1",
54
- "@crawlee/browser-pool": "4.0.0-rc.1",
55
- "@crawlee/cheerio": "4.0.0-rc.1",
56
- "@crawlee/core": "4.0.0-rc.1",
57
- "@crawlee/types": "4.0.0-rc.1",
58
- "@crawlee/utils": "4.0.0-rc.1",
59
- "cheerio": "^1.0.0",
60
- "jquery": "^3.7.1",
51
+ "@apify/timeout": "^1.1.0",
52
+ "@crawlee/basic": "4.0.0-rc.3",
53
+ "@crawlee/browser": "4.0.0-rc.3",
54
+ "@crawlee/browser-pool": "4.0.0-rc.3",
55
+ "@crawlee/cheerio": "4.0.0-rc.3",
56
+ "@crawlee/core": "4.0.0-rc.3",
57
+ "@crawlee/http-client": "4.0.0-rc.3",
58
+ "@crawlee/types": "4.0.0-rc.3",
59
+ "@crawlee/utils": "4.0.0-rc.3",
60
+ "cheerio": "^1.2.0",
61
+ "domhandler": "^6.0.1",
62
+ "jquery": "^3.8.0",
61
63
  "ml-logistic-regression": "^2.0.0",
62
- "ml-matrix": "^6.12.1",
64
+ "ml-matrix": "^6.15.1",
63
65
  "string-comparison": "^1.3.0",
64
- "tslib": "^2.8.1",
65
- "zod": "^4.5.4"
66
+ "tslib": "^2.9.1",
67
+ "zod": "^4.6.7"
66
68
  },
67
69
  "peerDependencies": {
68
70
  "playwright": "*"
@@ -79,5 +81,5 @@
79
81
  }
80
82
  }
81
83
  },
82
- "gitHead": "f354ca5e943bed1a5c657a1fce1974c053f9fff0"
84
+ "gitHead": "c8d256de99bcece26c9f675601dadaf0f2b892f2"
83
85
  }