@crawlee/playwright 4.0.0-beta.292 → 4.0.0-beta.294

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.
@@ -257,6 +257,11 @@ export declare class PlaywrightCrawler<ContextExtension = Dictionary<never>, Ext
257
257
  * Returns a `postNavigationHooks`-ready hook that runs {@link PlaywrightContextUtils.handleCloudflareChallenge}
258
258
  * and propagates the post-challenge {@link Response} back into the crawling context via its return value.
259
259
  *
260
+ * Cloudflare serves its challenge pages with a 403 status, which is part of the default `blockedStatusCodes`.
261
+ * Keep it there - the hook runs before the blocked-status check and replaces the response on a solved
262
+ * challenge, so solved requests pass it, while unsolved or undetected challenges keep the 403 and get
263
+ * retried with a fresh session.
264
+ *
260
265
  * **Example usage**
261
266
  * ```ts
262
267
  * import { PlaywrightCrawler, handleCloudflareChallengeHook } from 'crawlee';
@@ -159,7 +159,15 @@ export class PlaywrightCrawler extends BrowserCrawler {
159
159
  }),
160
160
  compileScript: (scriptString, ctx) => compileScript(scriptString, ctx),
161
161
  handleCloudflareChallenge: async (options) => {
162
- return handleCloudflareChallenge(context.page, context.request.url, options);
162
+ let response;
163
+ try {
164
+ response = context.response;
165
+ }
166
+ catch {
167
+ // the getter throws before navigation and with `skipNavigation`; a navigation
168
+ // without a response replaces it with plain `undefined` instead
169
+ }
170
+ return handleCloudflareChallenge(context.page, context.request.url, options, response);
163
171
  },
164
172
  };
165
173
  }
@@ -168,6 +176,11 @@ export class PlaywrightCrawler extends BrowserCrawler {
168
176
  * Returns a `postNavigationHooks`-ready hook that runs {@link PlaywrightContextUtils.handleCloudflareChallenge}
169
177
  * and propagates the post-challenge {@link Response} back into the crawling context via its return value.
170
178
  *
179
+ * Cloudflare serves its challenge pages with a 403 status, which is part of the default `blockedStatusCodes`.
180
+ * Keep it there - the hook runs before the blocked-status check and replaces the response on a solved
181
+ * challenge, so solved requests pass it, while unsolved or undetected challenges keep the 403 and get
182
+ * retried with a fresh session.
183
+ *
171
184
  * **Example usage**
172
185
  * ```ts
173
186
  * import { PlaywrightCrawler, handleCloudflareChallengeHook } from 'crawlee';
@@ -319,22 +319,29 @@ export interface HandleCloudflareChallengeOptions {
319
319
  *
320
320
  * On a successfully solved challenge the page is reloaded and the new {@link Response} is returned, so
321
321
  * it can be propagated back to the crawling context via a hook return value (see
322
- * {@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.
323
325
  *
324
326
  * Works best with camoufox.
325
327
  *
326
328
  * **Example usage**
327
329
  * ```ts
328
330
  * postNavigationHooks: [
329
- * 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
+ * },
330
336
  * ],
331
337
  * ```
332
338
  *
333
339
  * @param page Playwright [`Page`](https://playwright.dev/docs/api/class-page) object
334
340
  * @param url current URL for request identification, only used for logging
335
341
  * @param [options]
342
+ * @param [response] navigation response, used to poll for late-rendered challenge markup when it signals a likely challenge
336
343
  */
337
- 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>;
338
345
  export interface PlaywrightContextUtils {
339
346
  /**
340
347
  * Injects a JavaScript file into current `page`.
@@ -535,7 +542,11 @@ export interface PlaywrightContextUtils {
535
542
  * **Example usage**
536
543
  * ```ts
537
544
  * postNavigationHooks: [
538
- * 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
+ * },
539
550
  * ],
540
551
  * ```
541
552
  *
@@ -447,50 +447,74 @@ export async function parseWithCheerio(page, ignoreShadowRoots = false, ignoreIf
447
447
  *
448
448
  * On a successfully solved challenge the page is reloaded and the new {@link Response} is returned, so
449
449
  * it can be propagated back to the crawling context via a hook return value (see
450
- * {@link handleCloudflareChallengeHook}).
450
+ * {@link handleCloudflareChallengeHook}). Thanks to that, the 403 status of the challenge page does not
451
+ * need to be removed from `blockedStatusCodes` - a solved challenge replaces the response before the
452
+ * blocked-status check runs, and an unsolved one is retried with a fresh session.
451
453
  *
452
454
  * Works best with camoufox.
453
455
  *
454
456
  * **Example usage**
455
457
  * ```ts
456
458
  * postNavigationHooks: [
457
- * async (context) => ({ response: await context.handleCloudflareChallenge() }),
459
+ * async (context) => {
460
+ * const response = await context.handleCloudflareChallenge();
461
+ * // `{ response: undefined }` would replace the navigation response and skip the blocked-status check
462
+ * return response && { response };
463
+ * },
458
464
  * ],
459
465
  * ```
460
466
  *
461
467
  * @param page Playwright [`Page`](https://playwright.dev/docs/api/class-page) object
462
468
  * @param url current URL for request identification, only used for logging
463
469
  * @param [options]
470
+ * @param [response] navigation response, used to poll for late-rendered challenge markup when it signals a likely challenge
464
471
  */
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');
472
+ export async function handleCloudflareChallenge(page, url, options = {}, response) {
473
+ // The options object may outlive this call (the pre-wrapped hook reuses one instance for all
474
+ // requests and retries), so the defaults are kept local instead of being memoized on `options` -
475
+ // memoizing them would pin the closed-over `page` of the first call forever.
476
+ const isBlockedCallback = options.isBlockedCallback ??
477
+ (async (p) => {
478
+ const isBlocked = await p.evaluate(() => {
479
+ return document.querySelector('h1')?.textContent?.trim().includes('Sorry, you have been blocked');
480
+ });
481
+ return !!isBlocked;
469
482
  });
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');
483
+ const isChallengeCallback = options.isChallengeCallback ??
484
+ (async (p) => {
485
+ return await p.evaluate(async () => {
486
+ // Cloudflare keeps reshuffling the wrapper elements between `.footer-inner` and `.ray-id`,
487
+ // so only the stable outer classes are matched.
488
+ return !!document.querySelector('.footer .footer-inner .ray-id');
489
+ });
477
490
  });
478
- };
479
491
  const retryBlocked = async () => {
480
- const isBlocked = await options.isBlockedCallback(page).catch(() => false);
492
+ const isBlocked = await isBlockedCallback(page).catch(() => false);
481
493
  if (isBlocked) {
482
494
  throw new SessionError(`Blocked by Cloudflare when processing ${url}`);
483
495
  }
484
496
  };
485
497
  // check if we ended up on the CF challenge page
486
498
  const isChallenge = async () => {
487
- return options.isChallengeCallback(page).catch(async () => {
499
+ return isChallengeCallback(page).catch(async () => {
488
500
  // the challenge page navigates itself, which destroys the context of an in-flight check
489
501
  await page.waitForLoadState('domcontentloaded').catch(() => { });
490
- return options.isChallengeCallback(page).catch(() => false);
502
+ return isChallengeCallback(page).catch(() => false);
491
503
  });
492
504
  };
493
- if (!(await isChallenge())) {
505
+ // The challenge markup can finish rendering only after the `load` event, so when the response signals
506
+ // a likely challenge, poll for it instead of checking once. A 403 alone is not enough - it must come
507
+ // from Cloudflare (the `cf-ray` header), so 403s served by other stacks keep failing fast.
508
+ const headers = response?.headers() ?? {};
509
+ const likelyChallenge = headers['cf-mitigated'] === 'challenge' || (response?.status() === 403 && 'cf-ray' in headers);
510
+ let detected = await isChallenge();
511
+ for (let i = 0; !detected && likelyChallenge && i < 10; i++) {
512
+ // a hard-blocked page never turns into a challenge, so fail fast instead of finishing the poll
513
+ await retryBlocked();
514
+ await sleep(500);
515
+ detected = await isChallenge();
516
+ }
517
+ if (!detected) {
494
518
  await retryBlocked();
495
519
  return undefined;
496
520
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crawlee/playwright",
3
- "version": "4.0.0-beta.292",
3
+ "version": "4.0.0-beta.294",
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"
@@ -49,14 +49,14 @@
49
49
  "dependencies": {
50
50
  "@apify/datastructures": "^3.0.1",
51
51
  "@apify/timeout": "^1.0.1",
52
- "@crawlee/basic": "4.0.0-beta.292",
53
- "@crawlee/browser": "4.0.0-beta.292",
54
- "@crawlee/browser-pool": "4.0.0-beta.292",
55
- "@crawlee/cheerio": "4.0.0-beta.292",
56
- "@crawlee/core": "4.0.0-beta.292",
57
- "@crawlee/http-client": "4.0.0-beta.292",
58
- "@crawlee/types": "4.0.0-beta.292",
59
- "@crawlee/utils": "4.0.0-beta.292",
52
+ "@crawlee/basic": "4.0.0-beta.294",
53
+ "@crawlee/browser": "4.0.0-beta.294",
54
+ "@crawlee/browser-pool": "4.0.0-beta.294",
55
+ "@crawlee/cheerio": "4.0.0-beta.294",
56
+ "@crawlee/core": "4.0.0-beta.294",
57
+ "@crawlee/http-client": "4.0.0-beta.294",
58
+ "@crawlee/types": "4.0.0-beta.294",
59
+ "@crawlee/utils": "4.0.0-beta.294",
60
60
  "cheerio": "^1.2.0",
61
61
  "domhandler": "^6.0.1",
62
62
  "jquery": "^3.7.1",
@@ -81,5 +81,5 @@
81
81
  }
82
82
  }
83
83
  },
84
- "gitHead": "e7ce34549a48a7d15fca88b094291789efde4970"
84
+ "gitHead": "ce0c2764f8bec3ecc5a9bdaa0ed9227d8df805ee"
85
85
  }