@crawlee/playwright 4.0.0-beta.8 → 4.0.0-beta.80

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.
Files changed (31) hide show
  1. package/README.md +17 -13
  2. package/index.d.ts +0 -1
  3. package/index.js +0 -1
  4. package/internals/adaptive-playwright-crawler.d.ts +81 -58
  5. package/internals/adaptive-playwright-crawler.js +306 -208
  6. package/internals/enqueue-links/click-elements.d.ts +32 -14
  7. package/internals/enqueue-links/click-elements.js +57 -25
  8. package/internals/playwright-crawler.d.ts +96 -77
  9. package/internals/playwright-crawler.js +79 -38
  10. package/internals/playwright-launcher.d.ts +2 -1
  11. package/internals/playwright-launcher.js +1 -2
  12. package/internals/utils/playwright-utils.d.ts +54 -17
  13. package/internals/utils/playwright-utils.js +96 -83
  14. package/internals/utils/rendering-type-prediction.d.ts +9 -6
  15. package/internals/utils/rendering-type-prediction.js +58 -24
  16. package/package.json +16 -11
  17. package/index.d.ts.map +0 -1
  18. package/index.js.map +0 -1
  19. package/internals/adaptive-playwright-crawler.d.ts.map +0 -1
  20. package/internals/adaptive-playwright-crawler.js.map +0 -1
  21. package/internals/enqueue-links/click-elements.d.ts.map +0 -1
  22. package/internals/enqueue-links/click-elements.js.map +0 -1
  23. package/internals/playwright-crawler.d.ts.map +0 -1
  24. package/internals/playwright-crawler.js.map +0 -1
  25. package/internals/playwright-launcher.d.ts.map +0 -1
  26. package/internals/playwright-launcher.js.map +0 -1
  27. package/internals/utils/playwright-utils.d.ts.map +0 -1
  28. package/internals/utils/playwright-utils.js.map +0 -1
  29. package/internals/utils/rendering-type-prediction.d.ts.map +0 -1
  30. package/internals/utils/rendering-type-prediction.js.map +0 -1
  31. package/tsconfig.build.tsbuildinfo +0 -1
@@ -1,7 +1,7 @@
1
- import { BrowserCrawler, Configuration, Router } from '@crawlee/browser';
1
+ import { BrowserCrawler, RequestState, Router, serviceLocator } from '@crawlee/browser';
2
2
  import ow from 'ow';
3
3
  import { PlaywrightLauncher } from './playwright-launcher.js';
4
- import { gotoExtended, registerUtilsToContext } from './utils/playwright-utils.js';
4
+ import { gotoExtended, playwrightUtils } from './utils/playwright-utils.js';
5
5
  /**
6
6
  * Provides a simple framework for parallel crawling of web pages
7
7
  * using headless Chromium, Firefox and Webkit browsers with [Playwright](https://github.com/microsoft/playwright).
@@ -13,13 +13,15 @@ import { gotoExtended, registerUtilsToContext } from './utils/playwright-utils.j
13
13
  * If the target website doesn't need JavaScript, consider using {@link CheerioCrawler},
14
14
  * which downloads the pages using raw HTTP requests and is about 10x faster.
15
15
  *
16
- * The source URLs are represented using {@link Request} objects that are fed from
17
- * {@link RequestList} or {@link RequestQueue} instances provided by the {@link PlaywrightCrawlerOptions.requestList}
18
- * or {@link PlaywrightCrawlerOptions.requestQueue} constructor options, respectively.
16
+ * The source URLs are represented using {@link Request} objects that are fed from the
17
+ * {@link IRequestManager|request manager} provided via the {@link PlaywrightCrawlerOptions.requestManager|`requestManager`}
18
+ * constructor option (a {@link RequestQueue} is itself a request manager). To read from a read-only source such
19
+ * as a {@link RequestList} while still being able to enqueue new requests, combine it with a queue into a
20
+ * {@link RequestManagerTandem} via {@link IRequestLoader.toTandem|`requestLoader.toTandem()`} and pass the
21
+ * result as `requestManager`.
19
22
  *
20
- * If both {@link PlaywrightCrawlerOptions.requestList} and {@link PlaywrightCrawlerOptions.requestQueue} are used,
21
- * the instance first processes URLs from the {@link RequestList} and automatically enqueues all of them
22
- * to {@link RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.
23
+ * > The {@link PlaywrightCrawlerOptions.requestList|`requestList`} and {@link PlaywrightCrawlerOptions.requestQueue|`requestQueue`}
24
+ * > options are deprecated; they are still accepted and folded into a single `requestManager` for back-compat.
23
25
  *
24
26
  * The crawler finishes when there are no more {@link Request} objects to crawl.
25
27
  *
@@ -66,19 +68,19 @@ import { gotoExtended, registerUtilsToContext } from './utils/playwright-utils.j
66
68
  * @category Crawlers
67
69
  */
68
70
  export class PlaywrightCrawler extends BrowserCrawler {
69
- options;
70
- config;
71
71
  static optionsShape = {
72
72
  ...BrowserCrawler.optionsShape,
73
73
  browserPoolOptions: ow.optional.object,
74
74
  launcher: ow.optional.object,
75
+ ignoreIframes: ow.optional.boolean,
76
+ ignoreShadowRoots: ow.optional.boolean,
75
77
  };
76
78
  /**
77
79
  * All `PlaywrightCrawler` parameters are passed via an options object.
78
80
  */
79
- constructor(options = {}, config = Configuration.getGlobalConfig()) {
81
+ constructor(options = {}) {
80
82
  ow(options, 'PlaywrightCrawlerOptions', ow.object.exactShape(PlaywrightCrawler.optionsShape));
81
- const { launchContext = {}, headless, ...browserCrawlerOptions } = options;
83
+ const { launchContext = {}, headless, contextPipelineBuilder, ...browserCrawlerOptions } = options;
82
84
  const browserPoolOptions = {
83
85
  ...options.browserPoolOptions,
84
86
  };
@@ -95,45 +97,84 @@ export class PlaywrightCrawler extends BrowserCrawler {
95
97
  launchContext.launchOptions ??= {};
96
98
  launchContext.launchOptions.headless = headless;
97
99
  }
98
- const playwrightLauncher = new PlaywrightLauncher(launchContext, config);
100
+ const playwrightLauncher = new PlaywrightLauncher(launchContext, options.configuration);
99
101
  browserPoolOptions.browserPlugins = [playwrightLauncher.createBrowserPlugin()];
100
- super({ ...browserCrawlerOptions, launchContext, browserPoolOptions }, config);
101
- this.options = options;
102
- this.config = config;
102
+ super({
103
+ ...browserCrawlerOptions,
104
+ launchContext,
105
+ browserPoolOptions,
106
+ contextPipelineBuilder: contextPipelineBuilder ?? (() => this.buildContextPipeline()),
107
+ });
103
108
  }
104
- async _runRequestHandler(context) {
105
- registerUtilsToContext(context, this.options);
106
- await super._runRequestHandler(context);
109
+ buildContextPipeline() {
110
+ return super.buildContextPipeline().compose({ action: this.enhanceContext.bind(this) });
107
111
  }
108
112
  async _navigationHandler(crawlingContext, gotoOptions) {
109
113
  return gotoExtended(crawlingContext.page, crawlingContext.request, gotoOptions);
110
114
  }
115
+ async enhanceContext(context) {
116
+ const waitForSelector = async (selector, timeoutMs = 5_000) => {
117
+ const locator = context.page.locator(selector).first();
118
+ await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
119
+ };
120
+ const downloads = [];
121
+ context.page.on('download', (download) => downloads.push(download));
122
+ return {
123
+ injectFile: async (filePath, options) => playwrightUtils.injectFile(context.page, filePath, options),
124
+ injectJQuery: async () => {
125
+ if (context.request.state === RequestState.BEFORE_NAV) {
126
+ context.log.warning('Using injectJQuery() in preNavigationHooks leads to unstable results. Use it in a postNavigationHook or a requestHandler instead.');
127
+ await playwrightUtils.injectJQuery(context.page);
128
+ return;
129
+ }
130
+ await playwrightUtils.injectJQuery(context.page, { surviveNavigations: false });
131
+ },
132
+ blockRequests: async (options) => playwrightUtils.blockRequests(context.page, options),
133
+ waitForSelector,
134
+ parseWithCheerio: async (selector, timeoutMs = 5_000) => {
135
+ if (selector) {
136
+ await waitForSelector(selector, timeoutMs);
137
+ }
138
+ return playwrightUtils.parseWithCheerio(context.page, this.ignoreShadowRoots, this.ignoreIframes);
139
+ },
140
+ infiniteScroll: async (options) => playwrightUtils.infiniteScroll(context.page, options),
141
+ listDownloads: async () => downloads,
142
+ saveSnapshot: async (options) => playwrightUtils.saveSnapshot(context.page, { ...options, config: serviceLocator.getConfiguration() }),
143
+ enqueueLinksByClickingElements: async (options) => playwrightUtils.enqueueLinksByClickingElements({
144
+ ...options,
145
+ page: context.page,
146
+ requestManager: this.requestManager,
147
+ }),
148
+ compileScript: (scriptString, ctx) => playwrightUtils.compileScript(scriptString, ctx),
149
+ closeCookieModals: async () => playwrightUtils.closeCookieModals(context.page),
150
+ handleCloudflareChallenge: async (options) => {
151
+ return playwrightUtils.handleCloudflareChallenge(context.page, context.request.url, options);
152
+ },
153
+ };
154
+ }
111
155
  }
112
156
  /**
113
- * Creates new {@link Router} instance that works based on request labels.
114
- * This instance can then serve as a `requestHandler` of your {@link PlaywrightCrawler}.
115
- * Defaults to the {@link PlaywrightCrawlingContext}.
116
- *
117
- * > Serves as a shortcut for using `Router.create<PlaywrightCrawlingContext>()`.
157
+ * Returns a `postNavigationHooks`-ready hook that runs {@link PlaywrightContextUtils.handleCloudflareChallenge}
158
+ * and propagates the post-challenge {@link Response} back into the crawling context via its return value.
118
159
  *
160
+ * **Example usage**
119
161
  * ```ts
120
- * import { PlaywrightCrawler, createPlaywrightRouter } from 'crawlee';
121
- *
122
- * const router = createPlaywrightRouter();
123
- * router.addHandler('label-a', async (ctx) => {
124
- * ctx.log.info('...');
125
- * });
126
- * router.addDefaultHandler(async (ctx) => {
127
- * ctx.log.info('...');
128
- * });
162
+ * import { PlaywrightCrawler, handleCloudflareChallengeHook } from 'crawlee';
129
163
  *
130
164
  * const crawler = new PlaywrightCrawler({
131
- * requestHandler: router,
165
+ * postNavigationHooks: [handleCloudflareChallengeHook()],
132
166
  * });
133
- * await crawler.run();
134
167
  * ```
135
168
  */
136
- export function createPlaywrightRouter(routes) {
137
- return Router.create(routes);
169
+ export function handleCloudflareChallengeHook(options) {
170
+ return async (context) => {
171
+ const response = await context.handleCloudflareChallenge(options);
172
+ if (response !== undefined) {
173
+ return { response };
174
+ }
175
+ return undefined;
176
+ };
177
+ }
178
+ export function createPlaywrightRouter(routesOrSchemas) {
179
+ return Router.create(routesOrSchemas);
138
180
  }
139
- //# sourceMappingURL=playwright-crawler.js.map
@@ -84,6 +84,8 @@ export declare class PlaywrightLauncher extends BrowserLauncher<PlaywrightPlugin
84
84
  useIncognitoPages: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
85
85
  // @ts-ignore optional peer dependency or compatibility with es2022
86
86
  browserPerProxy: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
87
+ // @ts-ignore optional peer dependency or compatibility with es2022
88
+ ignoreProxyCertificate: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
87
89
  // @ts-ignore optional peer dependency or compatibility with es2022
88
90
  userDataDir: import("ow").StringPredicate & import("ow").BasePredicate<string | undefined>;
89
91
  // @ts-ignore optional peer dependency or compatibility with es2022
@@ -130,4 +132,3 @@ export declare class PlaywrightLauncher extends BrowserLauncher<PlaywrightPlugin
130
132
  * Promise that resolves to Playwright's `Browser` instance.
131
133
  */
132
134
  export declare function launchPlaywright(launchContext?: PlaywrightLaunchContext, config?: Configuration): Promise<Browser>;
133
- //# sourceMappingURL=playwright-launcher.d.ts.map
@@ -37,7 +37,7 @@ export class PlaywrightLauncher extends BrowserLauncher {
37
37
  * @ignore
38
38
  */
39
39
  function getDefaultExecutablePath(launchContext, config) {
40
- const pathFromPlaywrightImage = config.get('defaultBrowserPath');
40
+ const pathFromPlaywrightImage = config.defaultBrowserPath;
41
41
  const { launchOptions = {} } = launchContext;
42
42
  if (launchOptions.executablePath) {
43
43
  return launchOptions.executablePath;
@@ -87,4 +87,3 @@ export async function launchPlaywright(launchContext, config = Configuration.get
87
87
  const playwrightLauncher = new PlaywrightLauncher(launchContext, config);
88
88
  return playwrightLauncher.launch();
89
89
  }
90
- //# sourceMappingURL=playwright-launcher.js.map
@@ -17,14 +17,13 @@
17
17
  * ```
18
18
  * @module playwrightUtils
19
19
  */
20
- import { Configuration, type Request, type Session } from '@crawlee/browser';
20
+ import { Configuration, type Request } from '@crawlee/browser';
21
21
  import type { BatchAddRequestsResult } from '@crawlee/types';
22
22
  import { type CheerioRoot, type Dictionary } from '@crawlee/utils';
23
23
  // @ts-ignore optional peer dependency or compatibility with es2022
24
- import type { Page, Response } from 'playwright';
24
+ import type { Download, Page, Response } from 'playwright';
25
25
  import type { EnqueueLinksByClickingElementsOptions } from '../enqueue-links/click-elements.js';
26
26
  import { enqueueLinksByClickingElements } from '../enqueue-links/click-elements.js';
27
- import type { PlaywrightCrawlerOptions, PlaywrightCrawlingContext } from '../playwright-crawler.js';
28
27
  import { RenderingTypePredictor } from './rendering-type-prediction.js';
29
28
  export interface InjectFileOptions {
30
29
  /**
@@ -290,7 +289,7 @@ export declare function saveSnapshot(page: Page, options?: SaveSnapshotOptions):
290
289
  */
291
290
  export declare function parseWithCheerio(page: Page, ignoreShadowRoots?: boolean, ignoreIframes?: boolean): Promise<CheerioRoot>;
292
291
  export declare function closeCookieModals(page: Page): Promise<void>;
293
- interface HandleCloudflareChallengeOptions {
292
+ export interface HandleCloudflareChallengeOptions {
294
293
  /** Logging defaults to the `debug` level, use this flag to log to `info` level instead. */
295
294
  verbose?: boolean;
296
295
  /** How long should we wait after the challenge is completed for the final page to load. */
@@ -304,6 +303,13 @@ interface HandleCloudflareChallengeOptions {
304
303
  isChallengeCallback?: (page: Page) => Promise<boolean>;
305
304
  /** Allows overriding the detection of Cloudflare "blocked page". */
306
305
  isBlockedCallback?: (page: Page) => Promise<boolean>;
306
+ /** Allows overriding how the checkbox click position is calculated. */
307
+ clickPositionCallback?: (page: Page) => Promise<{
308
+ x: number;
309
+ y: number;
310
+ } | null>;
311
+ /** Optional delay (in seconds) before the first click attempt on the challenge checkbox. Defaults to 1s. */
312
+ preChallengeSleepSecs?: number;
307
313
  }
308
314
  /**
309
315
  * This helper tries to solve the Cloudflare challenge automatically by clicking on the checkbox.
@@ -312,23 +318,24 @@ interface HandleCloudflareChallengeOptions {
312
318
  * result in a SessionError which will be automatically retried, so only successful requests will get
313
319
  * into the `requestHandler`.
314
320
  *
321
+ * On a successfully solved challenge the page is reloaded and the new {@link Response} is returned, so
322
+ * it can be propagated back to the crawling context via a hook return value (see
323
+ * {@link handleCloudflareChallengeHook}).
324
+ *
315
325
  * Works best with camoufox.
316
326
  *
317
327
  * **Example usage**
318
328
  * ```ts
319
329
  * postNavigationHooks: [
320
- * async ({ handleCloudflareChallenge }) => {
321
- * await handleCloudflareChallenge();
322
- * },
330
+ * async (context) => ({ response: await context.handleCloudflareChallenge() }),
323
331
  * ],
324
332
  * ```
325
333
  *
326
334
  * @param page Playwright [`Page`](https://playwright.dev/docs/api/class-page) object
327
335
  * @param url current URL for request identification, only used for logging
328
- * @param [session] current session object
329
336
  * @param [options]
330
337
  */
331
- declare function handleCloudflareChallenge(page: Page, url: string, session?: Session, options?: HandleCloudflareChallengeOptions): Promise<void>;
338
+ declare function handleCloudflareChallenge(page: Page, url: string, options?: HandleCloudflareChallengeOptions): Promise<Response | undefined>;
332
339
  /** @internal */
333
340
  export interface PlaywrightContextUtils {
334
341
  /**
@@ -480,7 +487,7 @@ export interface PlaywrightContextUtils {
480
487
  *
481
488
  * @returns Promise that resolves to {@link BatchAddRequestsResult} object.
482
489
  */
483
- enqueueLinksByClickingElements(options: Omit<EnqueueLinksByClickingElementsOptions, 'page' | 'requestQueue'>): Promise<BatchAddRequestsResult>;
490
+ enqueueLinksByClickingElements(options: Omit<EnqueueLinksByClickingElementsOptions, 'page' | 'requestManager'>): Promise<BatchAddRequestsResult>;
484
491
  /**
485
492
  * Compiles a Playwright script into an async function that may be executed at any time
486
493
  * by providing it with the following object:
@@ -510,6 +517,15 @@ export interface PlaywrightContextUtils {
510
517
  compileScript(scriptString: string, ctx?: Dictionary): CompiledScriptFunction;
511
518
  /**
512
519
  * Tries to close cookie consent modals on the page. Based on the I Don't Care About Cookies browser extension.
520
+ *
521
+ * Note that this method requires the idcac-playwright package to be installed.
522
+ * Crawlee does not include it by default due to licensing issues.
523
+ *
524
+ * To use this method, please install the package manually by running:
525
+ *
526
+ * ```bash
527
+ * npm install idcac-playwright
528
+ * ```
513
529
  */
514
530
  closeCookieModals(): Promise<void>;
515
531
  /**
@@ -519,22 +535,44 @@ export interface PlaywrightContextUtils {
519
535
  * result in a SessionError which will be automatically retried, so only successful requests will get
520
536
  * into the `requestHandler`.
521
537
  *
522
- * Works best with camoufox.
538
+ * On a successfully solved challenge the page is reloaded and the new {@link Response} is returned,
539
+ * which can be returned from the hook to update the crawling context's `response`. For the common case,
540
+ * prefer the pre-wrapped {@link handleCloudflareChallengeHook} hook.
523
541
  *
524
542
  * **Example usage**
525
543
  * ```ts
526
544
  * postNavigationHooks: [
527
- * async ({ handleCloudflareChallenge }) => {
528
- * await handleCloudflareChallenge();
529
- * },
545
+ * async (context) => ({ response: await context.handleCloudflareChallenge() }),
530
546
  * ],
531
547
  * ```
532
548
  *
533
549
  * @param [options]
534
550
  */
535
- handleCloudflareChallenge(options?: HandleCloudflareChallengeOptions): Promise<void>;
551
+ handleCloudflareChallenge(options?: HandleCloudflareChallengeOptions): Promise<Response | undefined>;
552
+ /**
553
+ * Returns the list of {@link https://playwright.dev/docs/api/class-download | Download} objects
554
+ * collected during the current page navigation and request handler.
555
+ *
556
+ * Useful for accessing files that the page downloads automatically.
557
+ * For most use cases, prefer re-enqueueing the URL to {@link FileDownload}.
558
+ * Use this only when direct access to the Playwright `Download` object is required.
559
+ *
560
+ * **Example usage**
561
+ * ```ts
562
+ * requestHandler: async ({ listDownloads }) => {
563
+ * for (const download of await listDownloads()) {
564
+ * try {
565
+ * const stream = await download.createReadStream();
566
+ * // stream to storage...
567
+ * } catch {
568
+ * // download failed or was cancelled
569
+ * }
570
+ * }
571
+ * },
572
+ * ```
573
+ */
574
+ listDownloads(): Promise<Download[]>;
536
575
  }
537
- export declare function registerUtilsToContext(context: PlaywrightCrawlingContext, crawlerOptions: PlaywrightCrawlerOptions): void;
538
576
  export { enqueueLinksByClickingElements };
539
577
  /** @internal */
540
578
  export declare const playwrightUtils: {
@@ -551,4 +589,3 @@ export declare const playwrightUtils: {
551
589
  RenderingTypePredictor: typeof RenderingTypePredictor;
552
590
  handleCloudflareChallenge: typeof handleCloudflareChallenge;
553
591
  };
554
- //# sourceMappingURL=playwright-utils.d.ts.map