@crawlee/playwright 4.0.0-rc.2 → 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.
@@ -1,8 +1,8 @@
1
1
  import type { BrowserHook, LoadedRequest, RouterHandler, RouteSchemas, RoutesFromSchemas } from '@crawlee/browser';
2
- import type { BasicCrawlerOptions, CrawlingContext, EnqueueLinksOptions, GetUserDataFromRequest, RouterRoutes } from '@crawlee/basic';
2
+ import type { BasicCrawlerOptions, CrawlingContext, EnqueueLinksOptions, ExtractLinksOptions, GetUserDataFromRequest, RouterRoutes } from '@crawlee/basic';
3
3
  import { BasicCrawler } from '@crawlee/basic';
4
4
  import { CrawlingRequest } from '@crawlee/browser';
5
- import type { StorageTransactionView } from '@crawlee/core';
5
+ import type { AddRequestsBatchedResult, StorageTransactionView } from '@crawlee/core';
6
6
  import type { Dictionary, Awaitable } from '@crawlee/types';
7
7
  import { type Cheerio, type CheerioAPI } from 'cheerio';
8
8
  import type { AnyNode } from 'domhandler';
@@ -82,7 +82,18 @@ export interface AdaptivePlaywrightCrawlerContext<UserData extends Dictionary =
82
82
  * ```
83
83
  */
84
84
  parseWithCheerio(selector?: string, timeoutMs?: number): Promise<CheerioAPI>;
85
- enqueueLinks(options?: EnqueueLinksOptions): Promise<unknown>;
85
+ /**
86
+ * Extracts URLs from the current page, without adding them to the request queue.
87
+ * In a browser, it first waits for an element matching the selector, with a 5s timeout.
88
+ */
89
+ extractLinks(options?: ExtractLinksOptions): Promise<string[]>;
90
+ /**
91
+ * Extracts URLs from the current page and adds them to the request queue.
92
+ *
93
+ * By default, the requests are buffered until the crawler settles on this attempt's result, so the returned
94
+ * `requestId` of a newly added request is provisional, and nothing is added when the attempt is discarded.
95
+ */
96
+ enqueueLinks(options?: EnqueueLinksOptions): Promise<AddRequestsBatchedResult>;
86
97
  }
87
98
  interface AdaptiveHookContext extends Pick<AdaptivePlaywrightCrawlerContext, 'id' | 'session' | 'proxyInfo' | 'log' | 'extendTimeout'> {
88
99
  page?: Page;
@@ -1,6 +1,6 @@
1
1
  import { setTimeout as delay } from 'node:timers/promises';
2
2
  import { isDeepStrictEqual } from 'node:util';
3
- import { BasicCrawler, ContextPipeline, ContextPipelineInitializationError, ContextPipelineInterruptedError, navigationDeadlineKey, RequestHandlerError, resolveBaseUrlForEnqueueLinksFiltering, Router, Statistics, } from '@crawlee/basic';
3
+ import { BasicCrawler, ContextPipeline, ContextPipelineCleanupError, ContextPipelineInitializationError, ContextPipelineInterruptedError, navigationDeadlineKey, RequestHandlerError, resolveBaseUrlForEnqueueLinksFiltering, Router, Statistics, } from '@crawlee/basic';
4
4
  import { CrawlingRequest, extractUrlsFromPage } from '@crawlee/browser';
5
5
  import { CheerioCrawler } from '@crawlee/cheerio';
6
6
  import { ResponseWithUrl } from '@crawlee/http-client';
@@ -10,6 +10,86 @@ import { z } from 'zod';
10
10
  import { addTimeoutToPromise } from '@apify/timeout';
11
11
  import { PlaywrightCrawler } from './playwright-crawler.js';
12
12
  import { RenderingTypePredictor, } from './utils/rendering-type-prediction.js';
13
+ /**
14
+ * A failed attempt stops before its cleanups (closing the page) until released, so the error handlers still get an
15
+ * open page, as in `BasicCrawler`.
16
+ */
17
+ class Attempt {
18
+ transaction;
19
+ #failure = Promise.withResolvers();
20
+ #failed = false;
21
+ #cleanupsReleased = Promise.withResolvers();
22
+ #call;
23
+ #context;
24
+ #heldBeforeCleanups = false;
25
+ #releaseDeferred = false;
26
+ constructor(transaction) {
27
+ this.transaction = transaction;
28
+ this.#failure.promise.catch(() => { });
29
+ }
30
+ /** Settles without waiting for a failed run's cleanups. */
31
+ async run(pipeline, context, consumer) {
32
+ this.#context = context;
33
+ this.#call = pipeline.call(context, consumer, async (error) => {
34
+ this.#heldBeforeCleanups = true;
35
+ this.fail(error);
36
+ await this.#cleanupsReleased.promise;
37
+ throw error;
38
+ });
39
+ await Promise.race([this.#call, this.#failure.promise]);
40
+ }
41
+ fail(reason) {
42
+ this.#failed = true;
43
+ this.#failure.reject(reason);
44
+ }
45
+ /** Stops waiting for `handler` once the run fails - a timeout does not stop it. */
46
+ abandonable(handler) {
47
+ return async (context) => {
48
+ // The run may have failed before the handler starts - then it never starts.
49
+ if (this.#failed) {
50
+ return this.#failure.promise;
51
+ }
52
+ return Promise.race([handler(context), this.#failure.promise]);
53
+ };
54
+ }
55
+ /** Idempotent. */
56
+ async release() {
57
+ this.#cleanupsReleased.resolve();
58
+ // Not waited for if still in a middleware or a non-abandonable handler.
59
+ if (this.#heldBeforeCleanups) {
60
+ await this.#call?.catch((error) => {
61
+ if (error instanceof ContextPipelineCleanupError)
62
+ throw error;
63
+ });
64
+ }
65
+ }
66
+ /** Lets the error handlers, which get the outer `context`, use this attempt's page and helpers. */
67
+ exposeToErrorHandlers(context) {
68
+ this.#releaseDeferred = true;
69
+ // Before the attempt's own `registerDeferredCleanup` replaces the outer one below.
70
+ context.registerDeferredCleanup(async () => this.release());
71
+ const descriptors = Object.getOwnPropertyDescriptors(this.#context ?? {});
72
+ for (const key of Reflect.ownKeys(descriptors)) {
73
+ // The attempt-bound helpers (non-configurable, see `#crawlOne`) and the navigation deadline stay here.
74
+ if (descriptors[key].configurable === false || key === navigationDeadlineKey) {
75
+ delete descriptors[key];
76
+ }
77
+ }
78
+ Object.defineProperties(context, descriptors);
79
+ }
80
+ async settle() {
81
+ try {
82
+ if (!this.#releaseDeferred) {
83
+ await this.release();
84
+ }
85
+ }
86
+ finally {
87
+ // Closed even when a cleanup threw - the writes it still holds must never reach storage.
88
+ this.transaction.rollback();
89
+ this.transaction.dispose();
90
+ }
91
+ }
92
+ }
13
93
  const adaptiveStatisticStateSchema = z.object({
14
94
  /** How many requests were handled by the HTTP-only request handler. */
15
95
  httpOnlyRequestHandlerRuns: z.number().default(0),
@@ -134,7 +214,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
134
214
  this.#individualRequestHandlerTimeoutMillis = requestHandlerTimeoutSecs * 1000;
135
215
  // `renderingTypeDetectionRatio` only configures the default predictor - an injected one brings its own
136
216
  // detection ratio (and its own state), so the option is ignored in that case.
137
- this.#renderingTypePredictor = OwnedOrInjected.resolve(renderingTypePredictor, () => new RenderingTypePredictor({ detectionRatio: renderingTypeDetectionRatio }));
217
+ this.#renderingTypePredictor = OwnedOrInjected.resolve(renderingTypePredictor, () => new RenderingTypePredictor({ detectionRatio: renderingTypeDetectionRatio, id: options.id }));
138
218
  this.#attemptWritePolicy = {
139
219
  requestQueue: 'deferred',
140
220
  ...(typeof transactionalStorage === 'object' ? transactionalStorage : {}),
@@ -239,69 +319,81 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
239
319
  get parseWithCheerio() {
240
320
  throw new Error(errorMessage('parseWithCheerio'));
241
321
  },
322
+ get extractLinks() {
323
+ throw new Error(errorMessage('extractLinks'));
324
+ },
242
325
  get enqueueLinks() {
243
326
  throw new Error(errorMessage('enqueueLinks'));
244
327
  },
245
328
  }));
246
329
  }
247
330
  async #adaptCheerioContext(cheerioContext) {
331
+ const extractLinks = async (options = {}) => extractUrlsFromCheerio(cheerioContext.$, options.selector, options.baseUrl ?? cheerioContext.request.loadedUrl);
248
332
  return {
249
333
  get page() {
250
334
  throw new Error('Page object was used in HTTP-only request handler');
251
335
  },
252
- enqueueLinks: async (options = {}) => {
253
- const urls = extractUrlsFromCheerio(cheerioContext.$, options.selector, options.baseUrl ?? cheerioContext.request.loadedUrl);
254
- return (await this.#enqueueLinks(urls, options, cheerioContext.request));
255
- },
256
- // The HTTP crawler has already consumed the body; hand out a fresh copy, like the browser side does.
257
- // HTML bodies are already decoded to UTF-8, so `arrayBuffer()` may disagree with the original headers.
258
- response: new ResponseWithUrl(cheerioContext.body, cheerioContext.response),
336
+ extractLinks,
337
+ enqueueLinks: async (options = {}) => this.#enqueueLinks(await extractLinks(options), options, cheerioContext.request),
338
+ // `skipNavigation` keeps the inner throwing getter. The body is already consumed (and decoded to UTF-8).
339
+ ...(cheerioContext.request.skipNavigation
340
+ ? {}
341
+ : { response: new ResponseWithUrl(cheerioContext.body, cheerioContext.response) }),
259
342
  };
260
343
  }
261
344
  async #adaptPlaywrightContext(playwrightContext) {
262
- // Capture the original response to avoid infinite recursion when the getter is copied to the context
263
- const originalResponse = playwrightContext.response;
264
- // `headers()` can return repeated headers (e.g. `set-cookie`) joined with `\n`, which `Headers` rejects
265
- const headers = new Headers();
266
- for (const { name, value } of await originalResponse.headersArray()) {
267
- headers.append(name, value);
345
+ // Capture the original response to avoid infinite recursion when the getter is copied to the context.
346
+ // The inner getter throws with `skipNavigation` or when navigation produced no response; it then stays.
347
+ let originalResponse;
348
+ try {
349
+ originalResponse = playwrightContext.response;
268
350
  }
269
- return {
270
- response: new ResponseWithUrl(Uint8Array.from(await originalResponse.body()), {
351
+ catch { }
352
+ let response;
353
+ if (originalResponse) {
354
+ // `headers()` can return repeated headers (e.g. `set-cookie`) joined with `\n`, which `Headers` rejects
355
+ const headers = new Headers();
356
+ for (const { name, value } of await originalResponse.headersArray()) {
357
+ headers.append(name, value);
358
+ }
359
+ // `body()` throws for redirects, `304` cache hits included, and for responses the page navigated away from
360
+ const body = await originalResponse
361
+ .body()
362
+ .catch(async () => Buffer.from(await playwrightContext.page.content()));
363
+ response = new ResponseWithUrl(Uint8Array.from(body), {
271
364
  headers,
272
365
  status: originalResponse.status(),
273
366
  statusText: originalResponse.statusText(),
274
367
  url: originalResponse.url(),
275
- }),
276
- enqueueLinks: async (options = {}, timeoutMs = 5000) => {
277
- // TODO consider using `context.parseWithCheerio` to make this universal and avoid code duplication
278
- const selector = options.selector ?? 'a';
279
- const locator = playwrightContext.page.locator(selector).first();
280
- // Wait for client-rendered links, but like the HTTP side, enqueue nothing when there are none.
281
- await locator.waitFor({ timeout: timeoutMs, state: 'attached' }).catch((error) => {
282
- if (error.name !== 'TimeoutError')
283
- throw error;
284
- });
285
- const urls = await extractUrlsFromPage(playwrightContext.page, selector, options.baseUrl ?? playwrightContext.request.loadedUrl);
286
- return (await this.#enqueueLinks(urls, options, playwrightContext.request));
287
- },
368
+ });
369
+ }
370
+ const extractLinks = async (options = {}, timeoutMs = 5000) => {
371
+ // TODO consider using `context.parseWithCheerio` to make this universal and avoid code duplication
372
+ const selector = options.selector ?? 'a';
373
+ const locator = playwrightContext.page.locator(selector).first();
374
+ // Wait for client-rendered links, but like the HTTP side, return nothing when there are none.
375
+ await locator.waitFor({ timeout: timeoutMs, state: 'attached' }).catch((error) => {
376
+ if (error.name !== 'TimeoutError')
377
+ throw error;
378
+ });
379
+ return extractUrlsFromPage(playwrightContext.page, selector, options.baseUrl ?? playwrightContext.request.loadedUrl);
380
+ };
381
+ return {
382
+ ...(response && { response }),
383
+ extractLinks,
384
+ enqueueLinks: async (options = {}, timeoutMs = 5000) => this.#enqueueLinks(await extractLinks(options, timeoutMs), options, playwrightContext.request),
288
385
  };
289
386
  }
290
387
  /**
291
- * Runs one request handler attempt inside its own {@link StorageTransaction}, wrapping the inner
292
- * (static or browser) context pipeline. The transaction is pushed to `transactions` *at creation
293
- * time, before the `try`*, as failed attempts are routine here. The caller owns the outcome and
294
- * disposal, including closing or reverting the {@link ContextModifications}.
388
+ * Runs one request handler attempt inside the attempt's {@link StorageTransaction}, wrapping the inner
389
+ * (static or browser) context pipeline. The caller owns the outcome and settles the attempt, including
390
+ * closing or reverting the {@link ContextModifications}.
295
391
  *
296
392
  * `request` defaults to the context's; a detection rerun passes a copy so it sees the request as it
297
393
  * was before the browser attempt.
298
394
  */
299
- async #crawlOne(renderingType, context, useStateFunction, transactions, request = context.request) {
300
- const transaction = createStorageTransaction({
301
- policy: this.#attemptWritePolicy,
302
- commitTimeoutMillis: this.internalTimeoutMillis,
303
- });
304
- transactions.push(transaction);
395
+ async #crawlOne(renderingType, context, useStateFunction, attempt, request = context.request) {
396
+ const { transaction } = attempt;
305
397
  const logs = [];
306
398
  const contextModifications = {
307
399
  request: new MutationJournal(),
@@ -326,32 +418,13 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
326
418
  for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(attemptBoundContextHelpers))) {
327
419
  Object.defineProperty(subCrawlerContext, key, { ...descriptor, configurable: false });
328
420
  }
329
- // The timeout below does not stop the request handler, and the pipeline closes the page only after the handler
330
- // settles. Racing the handler against this lets a timed-out attempt release its page right away.
331
- const attemptFailed = new AbortController();
332
421
  try {
333
- // Any failure - middleware or handler - ends up in the `ok: false` branch below.
334
- const rethrow = (error) => {
335
- throw error;
336
- };
337
- const abandonableRequestHandler = async (crawlingContext) => {
338
- // The attempt may have failed before the handler starts, and a late abort listener would never fire.
339
- attemptFailed.signal.throwIfAborted();
340
- return Promise.race([
341
- this.requestHandler(crawlingContext),
342
- new Promise((_resolve, reject) => {
343
- attemptFailed.signal.addEventListener('abort', () => reject(attemptFailed.signal.reason), {
344
- once: true,
345
- });
346
- }),
347
- ]);
348
- };
349
422
  const callAdaptiveRequestHandler = async () => {
350
423
  if (renderingType === 'static') {
351
- await this.#staticContextPipeline.call(subCrawlerContext, this.requestHandler.bind(this), rethrow);
424
+ await attempt.run(this.#staticContextPipeline, subCrawlerContext, this.requestHandler.bind(this));
352
425
  }
353
426
  else if (renderingType === 'clientOnly') {
354
- await this.#browserContextPipeline.call(subCrawlerContext, abandonableRequestHandler, rethrow);
427
+ await attempt.run(this.#browserContextPipeline, subCrawlerContext, attempt.abandonable(this.requestHandler.bind(this)));
355
428
  }
356
429
  };
357
430
  // this crawler overrides `runRequestHandler` and times each rendering-type run itself, so it has
@@ -362,7 +435,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
362
435
  return { ok: true, transaction, contextModifications, logs };
363
436
  }
364
437
  catch (error) {
365
- attemptFailed.abort(error);
438
+ attempt.fail(error);
366
439
  return { ok: false, error, transaction, contextModifications, logs };
367
440
  }
368
441
  }
@@ -372,18 +445,25 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
372
445
  if (!shouldDetectRenderingType) {
373
446
  crawlingContext.log.debug(`Predicted rendering type ${renderingTypePrediction.renderingType} for ${crawlingContext.request.url}`);
374
447
  }
375
- // Every transaction created for this request - up to two, since the static-then-browser
376
- // fall-through and the browser-then-detection pair are mutually exclusive. Disposed in the
377
- // `finally` below, not earlier: the comparators read the journals after `crawlOne` returns.
378
- const transactions = [];
448
+ // Settled only in the `finally` below - the comparators read the journals after `crawlOne` returns.
449
+ const attempts = [];
450
+ const startAttempt = () => {
451
+ const attempt = new Attempt(createStorageTransaction({
452
+ policy: this.#attemptWritePolicy,
453
+ commitTimeoutMillis: this.internalTimeoutMillis,
454
+ }));
455
+ attempts.push(attempt);
456
+ return attempt;
457
+ };
379
458
  try {
380
459
  // A result the `resultChecker` rejected is as good as a detection saying the page needs a browser - but
381
460
  // only once the browser run has succeeded. A thrown error says nothing about rendering.
382
- let httpResultRejected = false;
461
+ let resultCheckerRejectedHttpResult = false;
383
462
  if (renderingTypePrediction.renderingType === 'static' && !shouldDetectRenderingType) {
384
463
  crawlingContext.log.debug(`Running HTTP-only request handler for ${crawlingContext.request.url}`);
385
464
  this.statistics.state.httpOnlyRequestHandlerRuns++;
386
- const plainHTTPRun = await this.#crawlOne('static', crawlingContext, crawlingContext.useState, transactions);
465
+ const httpAttempt = startAttempt();
466
+ const plainHTTPRun = await this.#crawlOne('static', crawlingContext, crawlingContext.useState, httpAttempt);
387
467
  if (plainHTTPRun.ok &&
388
468
  this.#resultChecker(plainHTTPRun.transaction, { request: crawlingContext.request })) {
389
469
  crawlingContext.log.debug(`HTTP-only request handler succeeded for ${crawlingContext.request.url}`);
@@ -401,25 +481,29 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
401
481
  if (actualError instanceof ContextPipelineInterruptedError ||
402
482
  (await this.#shouldPropagateError(actualError, crawlingContext))) {
403
483
  this.#keepContextModifications(plainHTTPRun.contextModifications);
484
+ httpAttempt.exposeToErrorHandlers(crawlingContext);
404
485
  throw actualError;
405
486
  }
406
487
  crawlingContext.log.exception(actualError, `HTTP-only request handler failed for ${crawlingContext.request.url}`);
488
+ await httpAttempt.release();
407
489
  }
408
490
  else {
409
491
  crawlingContext.log.warning(`HTTP-only request handler returned a suspicious result for ${crawlingContext.request.url}`);
410
492
  this.statistics.state.renderingTypeMispredictions++;
411
- httpResultRejected = true;
493
+ resultCheckerRejectedHttpResult = true;
412
494
  }
413
495
  // The browser attempt starts from the request and state as they were before the rejected one.
414
496
  this.#discardContextModifications(plainHTTPRun.contextModifications, crawlingContext);
415
497
  }
416
498
  crawlingContext.log.debug(`Running browser request handler for ${crawlingContext.request.url}`);
417
499
  this.statistics.state.browserRequestHandlerRuns++;
418
- const browserRun = await this.#crawlOne('clientOnly', crawlingContext, crawlingContext.useState, transactions);
500
+ const browserAttempt = startAttempt();
501
+ const browserRun = await this.#crawlOne('clientOnly', crawlingContext, crawlingContext.useState, browserAttempt);
419
502
  if (!browserRun.ok) {
420
503
  // A failed browser attempt is handed to the retry logic with its writes - `userData` stashed for the
421
504
  // next attempt must survive.
422
505
  this.#keepContextModifications(browserRun.contextModifications);
506
+ browserAttempt.exposeToErrorHandlers(crawlingContext);
423
507
  throw browserRun.error;
424
508
  }
425
509
  try {
@@ -432,7 +516,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
432
516
  this.#keepContextModifications(browserRun.contextModifications);
433
517
  }
434
518
  // Past the shutdown fence, `teardown()` has already drained - and possibly torn down the predictor.
435
- if (httpResultRejected && !this.#shutDown) {
519
+ if (resultCheckerRejectedHttpResult && !this.#shutDown) {
436
520
  this.#storeRenderingType(crawlingContext.request, 'clientOnly');
437
521
  }
438
522
  if (shouldDetectRenderingType) {
@@ -444,7 +528,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
444
528
  // away with it.
445
529
  const { request: requestJournal, state: stateJournal } = browserRun.contextModifications;
446
530
  let stateCopy;
447
- const plainHTTPRun = await this.#crawlOne('static', crawlingContext, async (defaultValue) => (stateCopy ??= stateJournal.undoOnto(JSON.parse(JSON.stringify(await crawlingContext.useState(defaultValue))))), transactions, requestJournal.undoOnto(CrawlingRequest.fromSchema(JSON.parse(JSON.stringify(crawlingContext.request)))));
531
+ const plainHTTPRun = await this.#crawlOne('static', crawlingContext, async (defaultValue) => (stateCopy ??= stateJournal.undoOnto(JSON.parse(JSON.stringify(await crawlingContext.useState(defaultValue))))), startAttempt(), requestJournal.undoOnto(CrawlingRequest.fromSchema(JSON.parse(JSON.stringify(crawlingContext.request)))));
448
532
  const detectionResult = (() => {
449
533
  if (!plainHTTPRun.ok) {
450
534
  return 'clientOnly';
@@ -469,11 +553,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
469
553
  }
470
554
  }
471
555
  finally {
472
- // A still-open transaction here belongs to a discarded attempt - roll it back, then release.
473
- for (const transaction of transactions) {
474
- transaction.rollback();
475
- transaction.dispose();
476
- }
556
+ await Promise.all(attempts.map(async (attempt) => attempt.settle()));
477
557
  }
478
558
  }
479
559
  #keepContextModifications(modifications) {
@@ -164,8 +164,6 @@ export declare class PlaywrightCrawler<ContextExtension = Dictionary<never>, Ext
164
164
  // @ts-ignore optional peer dependency or compatibility with es2022
165
165
  configuration: z.ZodOptional<z.ZodInstanceOf<import("@crawlee/browser").Configuration>>;
166
166
  storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
167
- // @ts-ignore optional peer dependency or compatibility with es2022
168
- eventManager: z.ZodOptional<z.ZodInstanceOf<import("@crawlee/browser").EventManager>>;
169
167
  logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
170
168
  minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
171
169
  maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
@@ -224,8 +222,6 @@ export declare class PlaywrightCrawler<ContextExtension = Dictionary<never>, Ext
224
222
  // @ts-ignore optional peer dependency or compatibility with es2022
225
223
  configuration: z.ZodOptional<z.ZodInstanceOf<import("@crawlee/browser").Configuration>>;
226
224
  storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
227
- // @ts-ignore optional peer dependency or compatibility with es2022
228
- eventManager: z.ZodOptional<z.ZodInstanceOf<import("@crawlee/browser").EventManager>>;
229
225
  logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
230
226
  minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
231
227
  maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
@@ -257,6 +253,11 @@ export declare class PlaywrightCrawler<ContextExtension = Dictionary<never>, Ext
257
253
  * Returns a `postNavigationHooks`-ready hook that runs {@link PlaywrightContextUtils.handleCloudflareChallenge}
258
254
  * and propagates the post-challenge {@link Response} back into the crawling context via its return value.
259
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
+ *
260
261
  * **Example usage**
261
262
  * ```ts
262
263
  * import { PlaywrightCrawler, handleCloudflareChallengeHook } from 'crawlee';
@@ -1,4 +1,5 @@
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
5
  import { playwrightBrowserPool } from './playwright-browser-pool.js';
@@ -107,7 +108,25 @@ export class PlaywrightCrawler extends BrowserCrawler {
107
108
  return this.buildContextPipeline().compose(this.#enhanceContext.bind(this));
108
109
  }
109
110
  async navigationHandler(crawlingContext, gotoOptions) {
110
- 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
+ }
111
130
  }
112
131
  async #enhanceContext(context) {
113
132
  const waitForSelector = async (selector, timeoutMs = 5_000) => {
@@ -159,7 +178,14 @@ export class PlaywrightCrawler extends BrowserCrawler {
159
178
  }),
160
179
  compileScript: (scriptString, ctx) => compileScript(scriptString, ctx),
161
180
  handleCloudflareChallenge: async (options) => {
162
- 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);
163
189
  },
164
190
  };
165
191
  }
@@ -168,6 +194,11 @@ export class PlaywrightCrawler extends BrowserCrawler {
168
194
  * Returns a `postNavigationHooks`-ready hook that runs {@link PlaywrightContextUtils.handleCloudflareChallenge}
169
195
  * and propagates the post-challenge {@link Response} back into the crawling context via its return value.
170
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
+ *
171
202
  * **Example usage**
172
203
  * ```ts
173
204
  * 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
  *
@@ -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,6 +4,12 @@ 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
  /**
@@ -36,7 +42,9 @@ export interface IRenderingTypePredictor {
36
42
  */
37
43
  export declare class RenderingTypePredictor implements IRenderingTypePredictor {
38
44
  #private;
39
- constructor({ detectionRatio, persistenceOptions }: RenderingTypePredictorOptions);
45
+ /** The identifier used in the default persistence key. */
46
+ readonly id: string;
47
+ constructor({ detectionRatio, id, persistenceOptions }: RenderingTypePredictorOptions);
40
48
  /**
41
49
  * Initialize the predictor by restoring persisted state.
42
50
  */
@@ -64,16 +64,20 @@ const stateCodec = z.codec(persistedState, predictorState, {
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
65
  */
66
66
  export class RenderingTypePredictor {
67
+ static #nextId = 0;
68
+ /** The identifier used in the default persistence key. */
69
+ id;
67
70
  #detectionRatio;
68
71
  #state;
69
- constructor({ detectionRatio, persistenceOptions }) {
72
+ constructor({ detectionRatio, id, persistenceOptions }) {
73
+ this.id = id != null ? String(id) : String(RenderingTypePredictor.#nextId++);
70
74
  this.#detectionRatio = detectionRatio;
71
75
  this.#state = new RecoverableState({
72
76
  defaultState: () => stateCodec.decode({}),
73
77
  // The codec validates in the decode direction, so it is a Standard Schema as-is; encoding needs a call.
74
78
  deserialize: stateCodec,
75
79
  serialize: (state) => stateCodec.encode(state),
76
- persistStateKey: 'rendering-type-predictor-state',
80
+ persistStateKey: `CRAWLEE_RENDERING_TYPE_PREDICTOR_STATE_${this.id}`,
77
81
  persistenceEnabled: true,
78
82
  ...persistenceOptions,
79
83
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crawlee/playwright",
3
- "version": "4.0.0-rc.2",
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,18 +48,18 @@
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.2",
53
- "@crawlee/browser": "4.0.0-rc.2",
54
- "@crawlee/browser-pool": "4.0.0-rc.2",
55
- "@crawlee/cheerio": "4.0.0-rc.2",
56
- "@crawlee/core": "4.0.0-rc.2",
57
- "@crawlee/http-client": "4.0.0-rc.2",
58
- "@crawlee/types": "4.0.0-rc.2",
59
- "@crawlee/utils": "4.0.0-rc.2",
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
60
  "cheerio": "^1.2.0",
61
61
  "domhandler": "^6.0.1",
62
- "jquery": "^3.7.1",
62
+ "jquery": "^3.8.0",
63
63
  "ml-logistic-regression": "^2.0.0",
64
64
  "ml-matrix": "^6.15.1",
65
65
  "string-comparison": "^1.3.0",
@@ -81,5 +81,5 @@
81
81
  }
82
82
  }
83
83
  },
84
- "gitHead": "a9b623229cd7d1bff5063fc82940efebaea47165"
84
+ "gitHead": "c8d256de99bcece26c9f675601dadaf0f2b892f2"
85
85
  }