@crawlee/playwright 4.0.0-rc.0 → 4.0.0-rc.2

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,5 +1,6 @@
1
1
  import { URL } from 'node:url';
2
- import { applyRequestTransform, constructUrlPatternObjects, createRequestOptions, filterRequestOptionsByPatterns, parseArgument, urlPatternSchema, Request as CrawleeRequest, schemas, serviceLocator, } from '@crawlee/browser';
2
+ import { applyRequestTransform, constructUrlPatternObjects, createRequestOptions, createSkippedRequestArgs, filterRequestOptionsByPatterns, urlPatternSchema, Request as CrawleeRequest, serviceLocator, } from '@crawlee/browser';
3
+ import { parseArgument, schemas } from '@crawlee/utils/internal';
3
4
  import { z } from 'zod';
4
5
  const STARTING_Z_INDEX = 2147400000;
5
6
  const getLog = () => serviceLocator.getChildLog('Playwright Click Elements');
@@ -64,6 +65,7 @@ export async function enqueueLinksByClickingElements(options) {
64
65
  const { page, requestManager, selector, clickOptions, include, exclude, transformRequestFunction, waitForPageIdleSecs, maxWaitForPageIdleSecs, forefront, onSkippedRequest, } = parsedOptions;
65
66
  const waitForPageIdleMillis = waitForPageIdleSecs * 1000;
66
67
  const maxWaitForPageIdleMillis = maxWaitForPageIdleSecs * 1000;
68
+ const hasOnSkippedRequest = onSkippedRequest !== undefined;
67
69
  const urlExcludePatternObjects = exclude?.length ? constructUrlPatternObjects(exclude) : [];
68
70
  const urlPatternObjects = include?.length ? constructUrlPatternObjects(include) : [];
69
71
  const interceptedRequests = await clickElementsAndInterceptNavigationRequests({
@@ -75,15 +77,15 @@ export async function enqueueLinksByClickingElements(options) {
75
77
  });
76
78
  const requestOptions = createRequestOptions(interceptedRequests, parsedOptions);
77
79
  const skippedByFilters = [];
78
- let filteredOptions = filterRequestOptionsByPatterns(requestOptions, urlPatternObjects.length > 0 ? urlPatternObjects : undefined, urlExcludePatternObjects, undefined, (url) => skippedByFilters.push(url));
80
+ let filteredOptions = filterRequestOptionsByPatterns(requestOptions, urlPatternObjects.length > 0 ? urlPatternObjects : undefined, urlExcludePatternObjects, undefined, hasOnSkippedRequest ? (opts) => skippedByFilters.push(opts) : undefined);
79
81
  if (onSkippedRequest && skippedByFilters.length > 0) {
80
- await Promise.all(skippedByFilters.map(async (url) => onSkippedRequest({ url, reason: 'filters' })));
82
+ await Promise.all(skippedByFilters.map(async (opts) => onSkippedRequest(createSkippedRequestArgs(opts, 'filters'))));
81
83
  }
82
84
  if (transformRequestFunction) {
83
85
  const skippedByTransform = [];
84
- filteredOptions = applyRequestTransform(filteredOptions, transformRequestFunction, (r) => skippedByTransform.push(r));
86
+ filteredOptions = applyRequestTransform(filteredOptions, transformRequestFunction, hasOnSkippedRequest ? (r) => skippedByTransform.push(r) : undefined);
85
87
  if (onSkippedRequest && skippedByTransform.length > 0) {
86
- await Promise.all(skippedByTransform.map(async (r) => onSkippedRequest({ url: r.url, reason: 'transform' })));
88
+ await Promise.all(skippedByTransform.map(async (r) => onSkippedRequest(createSkippedRequestArgs(r, 'transform'))));
87
89
  }
88
90
  }
89
91
  const requests = filteredOptions.map((opts) => new CrawleeRequest(opts));
@@ -1,8 +1,16 @@
1
- import type { Configuration } from '@crawlee/browser';
2
- import type { BrowserPool, BrowserPoolHooks, BrowserPoolOptions, PlaywrightPlugin, RemoteBrowserPool, RemoteBrowserPoolOptions } from '@crawlee/browser-pool';
1
+ import type { Configuration, CrawlerRemoteBrowserOptions } from '@crawlee/browser';
2
+ import type { BrowserPool, BrowserPoolHooks, BrowserPoolOptions, PlaywrightPlugin } from '@crawlee/browser-pool';
3
3
  // @ts-ignore optional peer dependency or compatibility with es2022
4
4
  import type { Page } from 'playwright';
5
5
  import type { PlaywrightLaunchContext } from './playwright-launcher.js';
6
+ /** {@link BrowserCrawlerOptions.remoteBrowser|`remoteBrowser`} for Playwright, with the protocol to connect over. */
7
+ export interface PlaywrightRemoteBrowserOptions extends CrawlerRemoteBrowserOptions {
8
+ /**
9
+ * `'cdp'` uses `connectOverCDP()` (the default), `'playwright'` uses `connect()` (Playwright's own WebSocket
10
+ * protocol, for endpoints started with `launchServer()`).
11
+ */
12
+ protocol?: 'cdp' | 'playwright';
13
+ }
6
14
  /** A {@link BrowserPool} of Playwright browsers, as built by {@link playwrightBrowserPool}. */
7
15
  export type PlaywrightBrowserPool = BrowserPool<{
8
16
  browserPlugins: [PlaywrightPlugin];
@@ -17,8 +25,8 @@ export interface PlaywrightBrowserPoolOptions extends Omit<BrowserPoolOptions, '
17
25
  headless?: boolean;
18
26
  /** Configuration to read the browser defaults from. Defaults to the global configuration. */
19
27
  configuration?: Configuration;
20
- }
21
- export interface RemotePlaywrightBrowserPoolOptions extends Pick<PlaywrightBrowserPoolOptions, 'launchContext' | 'headless' | 'configuration'>, Omit<RemoteBrowserPoolOptions, 'browserPlugins'> {
28
+ /** Connect to a remote browser service instead of launching locally; see {@link BrowserCrawlerOptions.remoteBrowser}. */
29
+ remoteBrowser?: PlaywrightRemoteBrowserOptions;
22
30
  }
23
31
  /**
24
32
  * Builds a {@link BrowserPool} of Playwright browsers to pass to a {@link PlaywrightCrawler} as its
@@ -45,27 +53,3 @@ export interface RemotePlaywrightBrowserPoolOptions extends Pick<PlaywrightBrows
45
53
  * @category Browser management
46
54
  */
47
55
  export declare function playwrightBrowserPool(options?: PlaywrightBrowserPoolOptions): PlaywrightBrowserPool;
48
- /**
49
- * The {@link RemoteBrowserPool} counterpart of {@link playwrightBrowserPool}: connects to a remote browser
50
- * service (Browserbase, Browserless, Steel, ...) with a Playwright plugin derived from `launchContext`.
51
- *
52
- * A {@link PlaywrightCrawler} accepts the same connection details directly via
53
- * {@link BrowserCrawlerOptions.remoteBrowser|`remoteBrowser`}; reach for this factory when you also need to
54
- * tune the wrapping pool, or to share one remote pool between crawlers.
55
- *
56
- * **Example usage:**
57
- *
58
- * ```javascript
59
- * const crawler = new PlaywrightCrawler({
60
- * browserPool: remotePlaywrightBrowserPool({
61
- * endpoint: 'wss://production-sfo.browserless.io?token=xxx',
62
- * maxOpenBrowsers: 2,
63
- * browserPoolOptions: { useFingerprints: false },
64
- * }),
65
- * requestHandler: async ({ page }) => { ... },
66
- * });
67
- * ```
68
- *
69
- * @category Browser management
70
- */
71
- export declare function remotePlaywrightBrowserPool(options: RemotePlaywrightBrowserPoolOptions): RemoteBrowserPool<Page>;
@@ -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
@@ -1,12 +1,12 @@
1
- import type { BrowserCrawlerOptions, BrowserCrawlingContext, BrowserHook, GetUserDataFromRequest, RequestHandler, RouterHandler, RouterRoutes, RouteSchemas, RoutesFromSchemas } from '@crawlee/browser';
1
+ import type { BrowserCrawlerOptions, BrowserCrawlingContext, BrowserHook, GetUserDataFromRequest, RouterHandler, RouterRoutes, RouteSchemas, RoutesFromSchemas } from '@crawlee/browser';
2
2
  import { BrowserCrawler } from '@crawlee/browser';
3
3
  import type { Dictionary } from '@crawlee/types';
4
4
  // @ts-ignore optional peer dependency or compatibility with es2022
5
- import type { Download, LaunchOptions, Page, Response } from 'playwright';
5
+ import type { Page, Response } from 'playwright';
6
6
  import { z } from 'zod';
7
- import type { EnqueueLinksByClickingElementsOptions } from './enqueue-links/click-elements.js';
7
+ import { type PlaywrightRemoteBrowserOptions } from './playwright-browser-pool.js';
8
8
  import type { PlaywrightLaunchContext } from './playwright-launcher.js';
9
- import type { BlockRequestsOptions, DirectNavigationOptions, HandleCloudflareChallengeOptions, InfiniteScrollOptions, InjectFileOptions, PlaywrightContextUtils, SaveSnapshotOptions } from './utils/playwright-utils.js';
9
+ import type { DirectNavigationOptions, HandleCloudflareChallengeOptions, PlaywrightContextUtils } from './utils/playwright-utils.js';
10
10
  export type PlaywrightGotoOptions = NonNullable<Parameters<Page['goto']>[1]>;
11
11
  export interface PlaywrightCrawlingContext<UserData extends Dictionary = any> extends BrowserCrawlingContext<Page, Response, UserData, PlaywrightGotoOptions>, PlaywrightContextUtils {
12
12
  }
@@ -21,29 +21,8 @@ export interface PlaywrightCrawlerOptions<ContextExtension = Dictionary<never>,
21
21
  * Can be also set via {@link Configuration}.
22
22
  */
23
23
  headless?: boolean;
24
- /**
25
- * Function that is called to process each request.
26
- *
27
- * The function receives the {@link PlaywrightCrawlingContext} as an argument, where:
28
- * - `request` is an instance of the {@link Request} object with details about the URL to open, HTTP method etc.
29
- * - `page` is an instance of the `Playwright`
30
- * [`Page`](https://playwright.dev/docs/api/class-page)
31
- * - `response` is an instance of the `Playwright`
32
- * [`Response`](https://playwright.dev/docs/api/class-response),
33
- * which is the main resource response as returned by `page.goto(request.url)`.
34
- *
35
- * The function must return a promise, which is then awaited by the crawler.
36
- *
37
- * If the function throws an exception, the crawler will try to re-crawl the
38
- * request later, up to `option.maxRequestRetries` times.
39
- * If all the retries fail, the crawler calls the function
40
- * provided to the `failedRequestHandler` parameter.
41
- * To make this work, you should **always**
42
- * let your function throw exceptions rather than catch them.
43
- * The exceptions are logged to the request using the
44
- * {@link Request.pushErrorMessage} function.
45
- */
46
- requestHandler?: RouterHandler<ExtendedContext, Routes> | RequestHandler<ExtendedContext>;
24
+ /** See {@link BrowserCrawlerOptions.remoteBrowser}; Playwright additionally lets you pick the `protocol`. */
25
+ remoteBrowser?: PlaywrightRemoteBrowserOptions;
47
26
  /**
48
27
  * Async functions that are sequentially evaluated before the navigation. Good for setting additional cookies
49
28
  * or browser properties before navigation. The function receives the `crawlingContext`; the options object
@@ -144,21 +123,12 @@ export interface PlaywrightCrawlerOptions<ContextExtension = Dictionary<never>,
144
123
  * ```
145
124
  * @category Crawlers
146
125
  */
147
- export declare class PlaywrightCrawler<ContextExtension = Dictionary<never>, ExtendedContext extends PlaywrightCrawlingContext = PlaywrightCrawlingContext & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<PlaywrightCrawlingContext['request']>>, StatisticStateExtension extends object = {}> extends BrowserCrawler<Page, Response, LaunchOptions, PlaywrightCrawlingContext, ContextExtension, ExtendedContext, Routes, StatisticStateExtension> {
126
+ export declare class PlaywrightCrawler<ContextExtension = Dictionary<never>, ExtendedContext extends PlaywrightCrawlingContext = PlaywrightCrawlingContext & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<PlaywrightCrawlingContext['request']>>, StatisticStateExtension extends object = {}> extends BrowserCrawler<Page, Response, PlaywrightCrawlingContext, ContextExtension, ExtendedContext, Routes, StatisticStateExtension> {
127
+ #private;
128
+ /**
129
+ * @internal
130
+ */
148
131
  protected static optionsShape: {
149
- headless: z.ZodOptional<z.ZodBoolean>;
150
- launcher: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
151
- navigationTimeoutSecs: z.ZodDefault<z.ZodCustom<number, number>>;
152
- preNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
153
- postNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
154
- launchContext: z.ZodDefault<z.ZodCustom<Dictionary, Dictionary>>;
155
- browserPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
156
- browserPoolBuilder: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
157
- remoteBrowser: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
158
- saveResponseCookies: z.ZodDefault<z.ZodBoolean>;
159
- proxyConfiguration: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
160
- ignoreIframes: z.ZodDefault<z.ZodBoolean>;
161
- ignoreShadowRoots: z.ZodDefault<z.ZodBoolean>;
162
132
  contextPipelineBuilder: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
163
133
  extendContext: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
164
134
  requestList: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
@@ -190,27 +160,23 @@ export declare class PlaywrightCrawler<ContextExtension = Dictionary<never>, Ext
190
160
  }, z.core.$strict>]>>;
191
161
  onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
192
162
  // @ts-ignore optional peer dependency or compatibility with es2022
193
- httpClient: z.ZodOptional<z.ZodCustom<import("@crawlee/http-client").BaseHttpClient, import("@crawlee/http-client").BaseHttpClient>>;
163
+ httpClient: z.ZodOptional<z.ZodInstanceOf<import("@crawlee/http-client").BaseHttpClient>>;
194
164
  // @ts-ignore optional peer dependency or compatibility with es2022
195
- configuration: z.ZodOptional<z.ZodCustom<import("@crawlee/browser").Configuration, import("@crawlee/browser").Configuration>>;
165
+ configuration: z.ZodOptional<z.ZodInstanceOf<import("@crawlee/browser").Configuration>>;
196
166
  storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
197
167
  // @ts-ignore optional peer dependency or compatibility with es2022
198
- eventManager: z.ZodOptional<z.ZodCustom<import("@crawlee/browser").EventManager, import("@crawlee/browser").EventManager>>;
168
+ eventManager: z.ZodOptional<z.ZodInstanceOf<import("@crawlee/browser").EventManager>>;
199
169
  logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
200
170
  minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
201
171
  maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
172
+ initialConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
202
173
  maxRequestsPerMinute: z.ZodOptional<z.ZodCustom<number, number>>;
203
174
  keepAlive: z.ZodOptional<z.ZodBoolean>;
204
175
  statistics: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
205
176
  id: z.ZodOptional<z.ZodString>;
206
- };
207
- protected static optionsSchema: z.ZodObject<{
208
- headless: z.ZodOptional<z.ZodBoolean>;
209
- launcher: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
210
177
  navigationTimeoutSecs: z.ZodDefault<z.ZodCustom<number, number>>;
211
178
  preNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
212
179
  postNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
213
- launchContext: z.ZodDefault<z.ZodCustom<Dictionary, Dictionary>>;
214
180
  browserPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
215
181
  browserPoolBuilder: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
216
182
  remoteBrowser: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
@@ -218,6 +184,11 @@ export declare class PlaywrightCrawler<ContextExtension = Dictionary<never>, Ext
218
184
  proxyConfiguration: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
219
185
  ignoreIframes: z.ZodDefault<z.ZodBoolean>;
220
186
  ignoreShadowRoots: z.ZodDefault<z.ZodBoolean>;
187
+ launchContext: z.ZodDefault<z.ZodCustom<Dictionary, Dictionary>>;
188
+ headless: z.ZodOptional<z.ZodBoolean>;
189
+ };
190
+ /** @internal */
191
+ protected static optionsSchema: z.ZodObject<{
221
192
  contextPipelineBuilder: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
222
193
  extendContext: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
223
194
  requestList: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
@@ -249,44 +220,38 @@ export declare class PlaywrightCrawler<ContextExtension = Dictionary<never>, Ext
249
220
  }, z.core.$strict>]>>;
250
221
  onSkippedRequest: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
251
222
  // @ts-ignore optional peer dependency or compatibility with es2022
252
- httpClient: z.ZodOptional<z.ZodCustom<import("@crawlee/http-client").BaseHttpClient, import("@crawlee/http-client").BaseHttpClient>>;
223
+ httpClient: z.ZodOptional<z.ZodInstanceOf<import("@crawlee/http-client").BaseHttpClient>>;
253
224
  // @ts-ignore optional peer dependency or compatibility with es2022
254
- configuration: z.ZodOptional<z.ZodCustom<import("@crawlee/browser").Configuration, import("@crawlee/browser").Configuration>>;
225
+ configuration: z.ZodOptional<z.ZodInstanceOf<import("@crawlee/browser").Configuration>>;
255
226
  storageBackend: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
256
227
  // @ts-ignore optional peer dependency or compatibility with es2022
257
- eventManager: z.ZodOptional<z.ZodCustom<import("@crawlee/browser").EventManager, import("@crawlee/browser").EventManager>>;
228
+ eventManager: z.ZodOptional<z.ZodInstanceOf<import("@crawlee/browser").EventManager>>;
258
229
  logger: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
259
230
  minConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
260
231
  maxConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
232
+ initialConcurrency: z.ZodOptional<z.ZodCustom<number, number>>;
261
233
  maxRequestsPerMinute: z.ZodOptional<z.ZodCustom<number, number>>;
262
234
  keepAlive: z.ZodOptional<z.ZodBoolean>;
263
235
  statistics: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
264
236
  id: z.ZodOptional<z.ZodString>;
237
+ navigationTimeoutSecs: z.ZodDefault<z.ZodCustom<number, number>>;
238
+ preNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
239
+ postNavigationHooks: z.ZodDefault<z.ZodCustom<unknown[], unknown[]>>;
240
+ browserPool: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
241
+ browserPoolBuilder: z.ZodOptional<z.ZodCustom<(...args: any[]) => unknown, (...args: any[]) => unknown>>;
242
+ remoteBrowser: z.ZodOptional<z.ZodCustom<Dictionary, Dictionary>>;
243
+ saveResponseCookies: z.ZodDefault<z.ZodBoolean>;
244
+ proxyConfiguration: z.ZodOptional<z.ZodType<Dictionary<any>, unknown, z.core.$ZodTypeInternals<Dictionary<any>, unknown>>>;
245
+ ignoreIframes: z.ZodDefault<z.ZodBoolean>;
246
+ ignoreShadowRoots: z.ZodDefault<z.ZodBoolean>;
247
+ launchContext: z.ZodDefault<z.ZodCustom<Dictionary, Dictionary>>;
248
+ headless: z.ZodOptional<z.ZodBoolean>;
265
249
  }, z.core.$strict>;
266
250
  /**
267
251
  * All `PlaywrightCrawler` parameters are passed via an options object.
268
252
  */
269
253
  constructor(options?: PlaywrightCrawlerOptions<ContextExtension, ExtendedContext, Routes, StatisticStateExtension>);
270
- // @ts-ignore optional peer dependency or compatibility with es2022
271
- protected buildContextPipeline(): import("@crawlee/browser").ContextPipeline<import("@crawlee/browser").CrawlingContext<Dictionary>, BrowserCrawlingContext<Page, Response, Dictionary, Dictionary> & {
272
- injectFile: (filePath: string, options?: InjectFileOptions) => Promise<unknown>;
273
- injectJQuery: () => Promise<void>;
274
- blockRequests: (options?: BlockRequestsOptions) => Promise<void>;
275
- waitForSelector: (selector: string, timeoutMs?: number) => Promise<void>;
276
- // @ts-ignore optional peer dependency or compatibility with es2022
277
- parseWithCheerio: (selector?: string, timeoutMs?: number) => Promise<import("@crawlee/browser").CheerioAPI>;
278
- infiniteScroll: (options?: InfiniteScrollOptions) => Promise<void>;
279
- listDownloads: () => Promise<Download[]>;
280
- saveSnapshot: (options?: SaveSnapshotOptions) => Promise<void>;
281
- // @ts-ignore optional peer dependency or compatibility with es2022
282
- enqueueLinksByClickingElements: (options: Omit<EnqueueLinksByClickingElementsOptions, "page" | "requestManager">) => Promise<import("@crawlee/types").BatchAddRequestsResult>;
283
- // @ts-ignore optional peer dependency or compatibility with es2022
284
- compileScript: (scriptString: string, ctx?: Dictionary) => import("./utils/playwright-utils.js").CompiledScriptFunction;
285
- closeCookieModals: () => Promise<void>;
286
- handleCloudflareChallenge: (options?: HandleCloudflareChallengeOptions) => Promise<Response | undefined>;
287
- }>;
288
254
  protected navigationHandler(crawlingContext: PlaywrightCrawlingContext, gotoOptions: DirectNavigationOptions): Promise<Response | null>;
289
- private enhanceContext;
290
255
  }
291
256
  /**
292
257
  * Returns a `postNavigationHooks`-ready hook that runs {@link PlaywrightContextUtils.handleCloudflareChallenge}
@@ -1,7 +1,8 @@
1
- import { assertBrowserPoolNotConfigured, BrowserCrawler, parseArgument, RequestState, Router, schemas, serviceLocator, } from '@crawlee/browser';
1
+ import { BrowserCrawler, RequestState, Router, serviceLocator } from '@crawlee/browser';
2
+ import { assertBrowserPoolNotConfigured, parseArgument, schemas } from '@crawlee/utils/internal';
2
3
  import { z } from 'zod';
3
- import { playwrightBrowserPool, remotePlaywrightBrowserPool } from './playwright-browser-pool.js';
4
- import { gotoExtended, playwrightUtils } from './utils/playwright-utils.js';
4
+ import { playwrightBrowserPool } from './playwright-browser-pool.js';
5
+ import { blockRequests, compileScript, enqueueLinksByClickingElements, gotoExtended, handleCloudflareChallenge, infiniteScroll, injectFile, injectJQuery, parseWithCheerio, saveSnapshot, } from './utils/playwright-utils.js';
5
6
  /**
6
7
  * Provides a simple framework for parallel crawling of web pages
7
8
  * using headless Chromium, Firefox and Webkit browsers with [Playwright](https://github.com/microsoft/playwright).
@@ -68,18 +69,22 @@ import { gotoExtended, playwrightUtils } from './utils/playwright-utils.js';
68
69
  * @category Crawlers
69
70
  */
70
71
  export class PlaywrightCrawler extends BrowserCrawler {
72
+ /**
73
+ * @internal
74
+ */
71
75
  static optionsShape = {
72
76
  ...BrowserCrawler.optionsShape,
77
+ launchContext: schemas.anyObject.default(() => ({})),
73
78
  headless: z.boolean().optional(),
74
- launcher: schemas.anyObject.optional(),
75
79
  };
80
+ /** @internal */
76
81
  static optionsSchema = z.strictObject(PlaywrightCrawler.optionsShape);
77
82
  /**
78
83
  * All `PlaywrightCrawler` parameters are passed via an options object.
79
84
  */
80
85
  constructor(options = {}) {
81
86
  const parsedOptions = parseArgument(options, PlaywrightCrawler.optionsSchema, 'PlaywrightCrawlerOptions');
82
- const { launchContext, headless, configuration, contextPipelineBuilder, ...browserCrawlerOptions } = parsedOptions;
87
+ const { launchContext, headless, configuration, ...browserCrawlerOptions } = parsedOptions;
83
88
  if (launchContext.proxyUrl) {
84
89
  throw new Error('PlaywrightCrawlerOptions.launchContext.proxyUrl is not allowed in PlaywrightCrawler.' +
85
90
  'Use PlaywrightCrawlerOptions.proxyConfiguration');
@@ -93,60 +98,68 @@ export class PlaywrightCrawler extends BrowserCrawler {
93
98
  }
94
99
  super({
95
100
  ...browserCrawlerOptions,
96
- launchContext,
97
101
  configuration,
98
- browserPoolBuilder: (remoteBrowser) => remoteBrowser
99
- ? remotePlaywrightBrowserPool({ ...remoteBrowser, launchContext, headless, configuration })
100
- : playwrightBrowserPool({ launchContext, headless, configuration }),
101
- contextPipelineBuilder: contextPipelineBuilder ?? (() => this.buildContextPipeline()),
102
+ browserPoolBuilder: (remoteBrowser) => playwrightBrowserPool({ launchContext, headless, configuration, remoteBrowser }),
103
+ contextPipelineBuilder: () => this.#buildContextPipeline(),
102
104
  });
103
105
  }
104
- buildContextPipeline() {
105
- return super.buildContextPipeline().compose({ action: this.enhanceContext.bind(this) });
106
+ #buildContextPipeline() {
107
+ return this.buildContextPipeline().compose(this.#enhanceContext.bind(this));
106
108
  }
107
109
  async navigationHandler(crawlingContext, gotoOptions) {
108
110
  return gotoExtended(crawlingContext.page, crawlingContext.request, gotoOptions);
109
111
  }
110
- async enhanceContext(context) {
112
+ async #enhanceContext(context) {
111
113
  const waitForSelector = async (selector, timeoutMs = 5_000) => {
112
114
  const locator = context.page.locator(selector).first();
113
115
  await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
114
116
  };
117
+ const parseWithCheerioFn = async (selector, timeoutMs = 5_000) => {
118
+ if (selector) {
119
+ await waitForSelector(selector, timeoutMs);
120
+ }
121
+ return parseWithCheerio(context.page, this.ignoreShadowRoots, this.ignoreIframes);
122
+ };
123
+ const querySelectorAll = async (selector, timeoutMs) => {
124
+ const matches = (await parseWithCheerioFn(selector, timeoutMs))(selector);
125
+ // The browser located it but the Cheerio snapshot does not have it - a Playwright-only selector,
126
+ // or an element under a shadow root/iframe the snapshot was told to ignore.
127
+ if (matches.length === 0) {
128
+ throw new Error(`Selector '${selector}' not found in the page snapshot.`);
129
+ }
130
+ return matches;
131
+ };
115
132
  const downloads = [];
116
133
  context.page.on('download', (download) => downloads.push(download));
117
134
  return {
118
- injectFile: async (filePath, options) => playwrightUtils.injectFile(context.page, filePath, options),
135
+ injectFile: async (filePath, options) => injectFile(context.page, filePath, options),
119
136
  injectJQuery: async () => {
120
137
  if (context.request.state === RequestState.BEFORE_NAV) {
121
138
  context.log.warning('Using injectJQuery() in preNavigationHooks leads to unstable results. Use it in a postNavigationHook or a requestHandler instead.');
122
- await playwrightUtils.injectJQuery(context.page);
139
+ await injectJQuery(context.page);
123
140
  return;
124
141
  }
125
- await playwrightUtils.injectJQuery(context.page, { surviveNavigations: false });
142
+ await injectJQuery(context.page, { surviveNavigations: false });
126
143
  },
127
- blockRequests: async (options) => playwrightUtils.blockRequests(context.page, options),
144
+ blockRequests: async (options) => blockRequests(context.page, options),
128
145
  waitForSelector,
129
- parseWithCheerio: async (selector, timeoutMs = 5_000) => {
130
- if (selector) {
131
- await waitForSelector(selector, timeoutMs);
132
- }
133
- return playwrightUtils.parseWithCheerio(context.page, this.ignoreShadowRoots, this.ignoreIframes);
134
- },
135
- infiniteScroll: async (options) => playwrightUtils.infiniteScroll(context.page, options),
146
+ parseWithCheerio: parseWithCheerioFn,
147
+ querySelectorAll,
148
+ querySelectorOne: async (selector, timeoutMs) => (await querySelectorAll(selector, timeoutMs)).first(),
149
+ infiniteScroll: async (options) => infiniteScroll(context.page, options),
136
150
  listDownloads: async () => downloads,
137
- saveSnapshot: async (options) => playwrightUtils.saveSnapshot(context.page, {
151
+ saveSnapshot: async (options) => saveSnapshot(context.page, {
138
152
  ...options,
139
153
  configuration: serviceLocator.getConfiguration(),
140
154
  }),
141
- enqueueLinksByClickingElements: async (options) => playwrightUtils.enqueueLinksByClickingElements({
155
+ enqueueLinksByClickingElements: async (options) => enqueueLinksByClickingElements({
142
156
  ...options,
143
157
  page: context.page,
144
158
  requestManager: this.requestManager,
145
159
  }),
146
- compileScript: (scriptString, ctx) => playwrightUtils.compileScript(scriptString, ctx),
147
- closeCookieModals: async () => playwrightUtils.closeCookieModals(context.page),
160
+ compileScript: (scriptString, ctx) => compileScript(scriptString, ctx),
148
161
  handleCloudflareChallenge: async (options) => {
149
- return playwrightUtils.handleCloudflareChallenge(context.page, context.request.url, options);
162
+ return handleCloudflareChallenge(context.page, context.request.url, options);
150
163
  },
151
164
  };
152
165
  }
@@ -72,11 +72,10 @@ export interface PlaywrightLaunchContext extends BrowserLaunchContext<LaunchOpti
72
72
  */
73
73
  export declare class PlaywrightLauncher extends BrowserLauncher<PlaywrightPlugin> {
74
74
  readonly configuration: Configuration;
75
+ /**
76
+ * @internal
77
+ */
75
78
  protected static optionsShape: {
76
- // @ts-ignore optional peer dependency or compatibility with es2022
77
- launcher: z.ZodOptional<z.ZodCustom<import("@crawlee/types").Dictionary, import("@crawlee/types").Dictionary>>;
78
- // @ts-ignore optional peer dependency or compatibility with es2022
79
- launchContextOptions: z.ZodOptional<z.ZodCustom<import("@crawlee/types").Dictionary, import("@crawlee/types").Dictionary>>;
80
79
  proxyUrl: z.ZodOptional<z.ZodURL>;
81
80
  useChrome: z.ZodOptional<z.ZodBoolean>;
82
81
  useIncognitoPages: z.ZodOptional<z.ZodBoolean>;
@@ -86,12 +85,11 @@ export declare class PlaywrightLauncher extends BrowserLauncher<PlaywrightPlugin
86
85
  // @ts-ignore optional peer dependency or compatibility with es2022
87
86
  launchOptions: z.ZodOptional<z.ZodCustom<import("@crawlee/types").Dictionary, import("@crawlee/types").Dictionary>>;
88
87
  userAgent: z.ZodOptional<z.ZodString>;
89
- };
90
- protected static optionsSchema: z.ZodObject<{
91
88
  // @ts-ignore optional peer dependency or compatibility with es2022
92
89
  launcher: z.ZodOptional<z.ZodCustom<import("@crawlee/types").Dictionary, import("@crawlee/types").Dictionary>>;
93
- // @ts-ignore optional peer dependency or compatibility with es2022
94
- launchContextOptions: z.ZodOptional<z.ZodCustom<import("@crawlee/types").Dictionary, import("@crawlee/types").Dictionary>>;
90
+ };
91
+ /** @internal */
92
+ protected static optionsSchema: z.ZodObject<{
95
93
  proxyUrl: z.ZodOptional<z.ZodURL>;
96
94
  useChrome: z.ZodOptional<z.ZodBoolean>;
97
95
  useIncognitoPages: z.ZodOptional<z.ZodBoolean>;
@@ -101,6 +99,8 @@ export declare class PlaywrightLauncher extends BrowserLauncher<PlaywrightPlugin
101
99
  // @ts-ignore optional peer dependency or compatibility with es2022
102
100
  launchOptions: z.ZodOptional<z.ZodCustom<import("@crawlee/types").Dictionary, import("@crawlee/types").Dictionary>>;
103
101
  userAgent: z.ZodOptional<z.ZodString>;
102
+ // @ts-ignore optional peer dependency or compatibility with es2022
103
+ launcher: z.ZodOptional<z.ZodCustom<import("@crawlee/types").Dictionary, import("@crawlee/types").Dictionary>>;
104
104
  }, z.core.$strict>;
105
105
  /**
106
106
  * All `PlaywrightLauncher` parameters are passed via this launchContext object.
@@ -1,5 +1,6 @@
1
- import { BrowserLauncher, Configuration, parseArgument, schemas } from '@crawlee/browser';
2
- import { PlaywrightPlugin } from '@crawlee/browser-pool';
1
+ import { BrowserLauncher, Configuration } from '@crawlee/browser';
2
+ import { PlaywrightPlugin, RemotePlaywrightPlugin } from '@crawlee/browser-pool';
3
+ import { parseArgument, schemas } from '@crawlee/utils/internal';
3
4
  import { z } from 'zod';
4
5
  /**
5
6
  * `PlaywrightLauncher` is based on the `BrowserLauncher`. It launches `playwright` browser instance.
@@ -7,12 +8,15 @@ import { z } from 'zod';
7
8
  */
8
9
  export class PlaywrightLauncher extends BrowserLauncher {
9
10
  configuration;
11
+ /**
12
+ * @internal
13
+ */
10
14
  static optionsShape = {
11
15
  ...BrowserLauncher.optionsShape,
12
- // Passthrough schemas — the launcher module object must keep its prototype through parsing.
16
+ // Passthrough schema — the launcher module object must keep its prototype through parsing.
13
17
  launcher: schemas.anyObject.optional(),
14
- launchContextOptions: schemas.anyObject.optional(),
15
18
  };
19
+ /** @internal */
16
20
  static optionsSchema = z.strictObject(PlaywrightLauncher.optionsShape);
17
21
  /**
18
22
  * All `PlaywrightLauncher` parameters are passed via this launchContext object.
@@ -31,6 +35,7 @@ export class PlaywrightLauncher extends BrowserLauncher {
31
35
  }, configuration);
32
36
  this.configuration = configuration;
33
37
  this.Plugin = PlaywrightPlugin;
38
+ this.RemotePlugin = RemotePlaywrightPlugin;
34
39
  }
35
40
  }
36
41
  /**
@@ -19,12 +19,12 @@
19
19
  */
20
20
  import { Configuration, type Request } from '@crawlee/browser';
21
21
  import type { BatchAddRequestsResult, Dictionary } from '@crawlee/types';
22
- import { type CheerioRoot } from '@crawlee/utils/internal';
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';
26
27
  import { enqueueLinksByClickingElements } from '../enqueue-links/click-elements.js';
27
- import { RenderingTypePredictor } from './rendering-type-prediction.js';
28
28
  export interface InjectFileOptions {
29
29
  /**
30
30
  * Enables the injected script to survive page navigations and reloads without need to be re-injected manually.
@@ -287,8 +287,7 @@ export declare function saveSnapshot(page: Page, options?: SaveSnapshotOptions):
287
287
  * @param page Playwright [`Page`](https://playwright.dev/docs/api/class-page) object.
288
288
  * @param ignoreShadowRoots
289
289
  */
290
- export declare function parseWithCheerio(page: Page, ignoreShadowRoots?: boolean, ignoreIframes?: boolean): Promise<CheerioRoot>;
291
- export declare function closeCookieModals(page: Page): Promise<void>;
290
+ export declare function parseWithCheerio(page: Page, ignoreShadowRoots?: boolean, ignoreIframes?: boolean): Promise<CheerioAPI>;
292
291
  export interface HandleCloudflareChallengeOptions {
293
292
  /** Logging defaults to the `debug` level, use this flag to log to `info` level instead. */
294
293
  verbose?: boolean;
@@ -335,7 +334,7 @@ export interface HandleCloudflareChallengeOptions {
335
334
  * @param url current URL for request identification, only used for logging
336
335
  * @param [options]
337
336
  */
338
- declare function handleCloudflareChallenge(page: Page, url: string, options?: HandleCloudflareChallengeOptions): Promise<Response | undefined>;
337
+ export declare function handleCloudflareChallenge(page: Page, url: string, options?: HandleCloudflareChallengeOptions): Promise<Response | undefined>;
339
338
  export interface PlaywrightContextUtils {
340
339
  /**
341
340
  * Injects a JavaScript file into current `page`.
@@ -422,6 +421,15 @@ export interface PlaywrightContextUtils {
422
421
  * ```
423
422
  */
424
423
  waitForSelector(selector: string, timeoutMs?: number): Promise<void>;
424
+ /**
425
+ * Like {@link PlaywrightContextUtils.waitForSelector|`waitForSelector`}, but returns the matched elements
426
+ * as a Cheerio object. Throws when nothing matches.
427
+ */
428
+ querySelectorAll(selector: string, timeoutMs?: number): Promise<Cheerio<AnyNode>>;
429
+ /**
430
+ * Like {@link PlaywrightContextUtils.querySelectorAll|`querySelectorAll`}, but returns only the first match.
431
+ */
432
+ querySelectorOne(selector: string, timeoutMs?: number): Promise<Cheerio<AnyNode>>;
425
433
  /**
426
434
  * Returns Cheerio handle for `page.content()`, allowing to work with the data same way as with {@link CheerioCrawler}.
427
435
  * When provided with the `selector` argument, it waits for it to be available first.
@@ -434,7 +442,7 @@ export interface PlaywrightContextUtils {
434
442
  * });
435
443
  * ```
436
444
  */
437
- parseWithCheerio(selector?: string, timeoutMs?: number): Promise<CheerioRoot>;
445
+ parseWithCheerio(selector?: string, timeoutMs?: number): Promise<CheerioAPI>;
438
446
  /**
439
447
  * Scrolls to the bottom of a page, or until it times out.
440
448
  * Loads dynamic content when it hits the bottom of a page, and then continues scrolling.
@@ -513,19 +521,6 @@ export interface PlaywrightContextUtils {
513
521
  * secured copies beforehand.
514
522
  */
515
523
  compileScript(scriptString: string, ctx?: Dictionary): CompiledScriptFunction;
516
- /**
517
- * Tries to close cookie consent modals on the page. Based on the I Don't Care About Cookies browser extension.
518
- *
519
- * Note that this method requires the idcac-playwright package to be installed.
520
- * Crawlee does not include it by default due to licensing issues.
521
- *
522
- * To use this method, please install the package manually by running:
523
- *
524
- * ```bash
525
- * npm install idcac-playwright
526
- * ```
527
- */
528
- closeCookieModals(): Promise<void>;
529
524
  /**
530
525
  * This helper tries to solve the Cloudflare challenge automatically by clicking on the checkbox.
531
526
  * It will try to detect the Cloudflare page, click on the checkbox, and wait for 10 seconds (configurable
@@ -572,18 +567,3 @@ export interface PlaywrightContextUtils {
572
567
  listDownloads(): Promise<Download[]>;
573
568
  }
574
569
  export { enqueueLinksByClickingElements };
575
- /** @internal */
576
- export declare const playwrightUtils: {
577
- injectFile: typeof injectFile;
578
- injectJQuery: typeof injectJQuery;
579
- gotoExtended: typeof gotoExtended;
580
- blockRequests: typeof blockRequests;
581
- enqueueLinksByClickingElements: typeof enqueueLinksByClickingElements;
582
- parseWithCheerio: typeof parseWithCheerio;
583
- infiniteScroll: typeof infiniteScroll;
584
- saveSnapshot: typeof saveSnapshot;
585
- compileScript: typeof compileScript;
586
- closeCookieModals: typeof closeCookieModals;
587
- RenderingTypePredictor: typeof RenderingTypePredictor;
588
- handleCloudflareChallenge: typeof handleCloudflareChallenge;
589
- };