@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,4 +1,4 @@
1
- import type { GlobInput, PseudoUrlInput, RegExpInput, RequestProvider, RequestTransform } from '@crawlee/browser';
1
+ import type { GlobInput, IRequestManager, PseudoUrlInput, RegExpInput, RequestTransform, SkippedRequestCallback } from '@crawlee/browser';
2
2
  import type { BatchAddRequestsResult, Dictionary } from '@crawlee/types';
3
3
  // @ts-ignore optional peer dependency or compatibility with es2022
4
4
  import type { Page } from 'playwright';
@@ -9,9 +9,9 @@ export interface EnqueueLinksByClickingElementsOptions {
9
9
  */
10
10
  page: Page;
11
11
  /**
12
- * A request queue to which the URLs will be enqueued.
12
+ * * A request manager to which the URLs will be enqueued.
13
13
  */
14
- requestQueue: RequestProvider;
14
+ requestManager: IRequestManager;
15
15
  /**
16
16
  * A CSS selector matching elements to be clicked on. Unlike in {@link enqueueLinks}, there is no default
17
17
  * value. This is to prevent suboptimal use of this function by using it too broadly.
@@ -40,6 +40,16 @@ export interface EnqueueLinksByClickingElementsOptions {
40
40
  * after clicking on elements matching the provided CSS selector.
41
41
  */
42
42
  globs?: GlobInput[];
43
+ /**
44
+ * An array of glob pattern strings, regexp patterns or plain objects
45
+ * containing patterns matching URLs that will **never** be enqueued.
46
+ *
47
+ * The plain objects must include either the `glob` property or the `regexp` property.
48
+ *
49
+ * Glob matching is always case-insensitive.
50
+ * If you need case-sensitive matching, provide a regexp.
51
+ */
52
+ exclude?: readonly (GlobInput | RegExpInput)[];
43
53
  /**
44
54
  * An array of regular expressions or plain objects
45
55
  * containing regular expressions matching the URLs to be enqueued.
@@ -73,25 +83,28 @@ export interface EnqueueLinksByClickingElementsOptions {
73
83
  */
74
84
  pseudoUrls?: PseudoUrlInput[];
75
85
  /**
76
- * Just before a new {@link Request} is constructed and enqueued to the {@link RequestQueue}, this function can be used
77
- * to remove it or modify its contents such as `userData`, `payload` or, most importantly `uniqueKey`. This is useful
78
- * when you need to enqueue multiple `Requests` to the queue that share the same URL, but differ in methods or payloads,
79
- * or to dynamically update or create `userData`.
80
- *
81
- * For example: by adding `useExtendedUniqueKey: true` to the `request` object, `uniqueKey` will be computed from
82
- * a combination of `url`, `method` and `payload` which enables crawling of websites that navigate using form submits
83
- * (POST requests).
86
+ * After {@link Request} objects are constructed and filtered by URL patterns (`globs`, `regexps`, `pseudoUrls`),
87
+ * this function can be used to remove them or modify their contents such as `userData`, `payload` or, most importantly
88
+ * `uniqueKey`. This is useful when you need to enqueue multiple `Requests` to the queue that share the same URL,
89
+ * but differ in methods or payloads, or to dynamically update or create `userData`.
84
90
  *
85
91
  * **Example:**
86
92
  * ```javascript
87
93
  * {
88
94
  * transformRequestFunction: (request) => {
89
95
  * request.userData.foo = 'bar';
90
- * request.useExtendedUniqueKey = true;
91
96
  * return request;
92
97
  * }
93
98
  * }
94
99
  * ```
100
+ *
101
+ * Note that `transformRequestFunction` has the highest priority and can overwrite request options
102
+ * specified in `globs`, `regexps`, or `pseudoUrls` objects, as well as the global `label` option.
103
+ *
104
+ * The function receives a {@link RequestOptions} object and can return either:
105
+ * - The modified {@link RequestOptions} object
106
+ * - `'unchanged'` to keep the original options as-is
107
+ * - A falsy value or `'skip'` to exclude the request from the queue
95
108
  */
96
109
  transformRequestFunction?: RequestTransform;
97
110
  /**
@@ -131,6 +144,12 @@ export interface EnqueueLinksByClickingElementsOptions {
131
144
  * @default false
132
145
  */
133
146
  skipNavigation?: boolean;
147
+ /**
148
+ * When a request is skipped for some reason, you can use this callback to act on it.
149
+ * This is fired for requests skipped because they don't match enqueueLinks filters
150
+ * or because they were removed by `transformRequestFunction`.
151
+ */
152
+ onSkippedRequest?: SkippedRequestCallback;
134
153
  }
135
154
  /**
136
155
  * The function finds elements matching a specific CSS selector in a Playwright page,
@@ -162,7 +181,7 @@ export interface EnqueueLinksByClickingElementsOptions {
162
181
  * ```javascript
163
182
  * await playwrightUtils.enqueueLinksByClickingElements({
164
183
  * page,
165
- * requestQueue,
184
+ * requestManager,
166
185
  * selector: 'a.product-detail',
167
186
  * pseudoUrls: [
168
187
  * 'https://www.example.com/handbags/[.*]'
@@ -200,4 +219,3 @@ export declare function clickElementsAndInterceptNavigationRequests(options: Cli
200
219
  */
201
220
  export declare function clickElements(page: Page, selector: string, clickOptions?: ClickOptions): Promise<void>;
202
221
  export {};
203
- //# sourceMappingURL=click-elements.d.ts.map
@@ -1,9 +1,8 @@
1
1
  import { URL } from 'node:url';
2
- import { constructGlobObjectsFromGlobs, constructRegExpObjectsFromPseudoUrls, constructRegExpObjectsFromRegExps, createRequestOptions, createRequests, } from '@crawlee/browser';
2
+ import { applyRequestTransform, constructGlobObjectsFromGlobs, constructRegExpObjectsFromPseudoUrls, constructRegExpObjectsFromRegExps, createRequestOptions, filterRequestOptionsByPatterns, Request as CrawleeRequest, serviceLocator, } from '@crawlee/browser';
3
3
  import ow from 'ow';
4
- import log_ from '@apify/log';
5
4
  const STARTING_Z_INDEX = 2147400000;
6
- const log = log_.child({ prefix: 'Playwright Click Elements' });
5
+ const getLog = () => serviceLocator.getChildLog('Playwright Click Elements');
7
6
  /**
8
7
  * The function finds elements matching a specific CSS selector in a Playwright page,
9
8
  * clicks all those elements using a mouse move and a left mouse button click and intercepts
@@ -34,7 +33,7 @@ const log = log_.child({ prefix: 'Playwright Click Elements' });
34
33
  * ```javascript
35
34
  * await playwrightUtils.enqueueLinksByClickingElements({
36
35
  * page,
37
- * requestQueue,
36
+ * requestManager,
38
37
  * selector: 'a.product-detail',
39
38
  * pseudoUrls: [
40
39
  * 'https://www.example.com/handbags/[.*]'
@@ -48,26 +47,41 @@ const log = log_.child({ prefix: 'Playwright Click Elements' });
48
47
  export async function enqueueLinksByClickingElements(options) {
49
48
  ow(options, ow.object.exactShape({
50
49
  page: ow.object.hasKeys('goto', 'evaluate'),
51
- requestQueue: ow.object.hasKeys('fetchNextRequest', 'addRequest'),
50
+ requestManager: ow.object.hasKeys('fetchNextRequest', 'addRequestsBatched'),
52
51
  selector: ow.string,
53
52
  userData: ow.optional.object,
54
- clickOptions: ow.optional.object.hasKeys('clickCount', 'delay'),
53
+ clickOptions: ow.optional.object,
55
54
  pseudoUrls: ow.optional.array.ofType(ow.any(ow.string, ow.object.hasKeys('purl'))),
56
55
  globs: ow.optional.array.ofType(ow.any(ow.string, ow.object.hasKeys('glob'))),
57
56
  regexps: ow.optional.array.ofType(ow.any(ow.regExp, ow.object.hasKeys('regexp'))),
57
+ exclude: ow.optional.array.ofType(ow.any(ow.string, ow.regExp, ow.object.hasKeys('glob'), ow.object.hasKeys('regexp'))),
58
58
  transformRequestFunction: ow.optional.function,
59
59
  waitForPageIdleSecs: ow.optional.number,
60
60
  maxWaitForPageIdleSecs: ow.optional.number,
61
61
  label: ow.optional.string,
62
62
  forefront: ow.optional.boolean,
63
63
  skipNavigation: ow.optional.boolean,
64
+ onSkippedRequest: ow.optional.function,
64
65
  }));
65
- const { page, requestQueue, selector, clickOptions, pseudoUrls, globs, regexps, transformRequestFunction, waitForPageIdleSecs = 1, maxWaitForPageIdleSecs = 5, forefront, } = options;
66
+ const { page, requestManager, selector, clickOptions,
67
+ // oxlint-disable-next-line typescript/no-deprecated -- still accepted for backwards compat
68
+ pseudoUrls, globs, regexps, transformRequestFunction, waitForPageIdleSecs = 1, maxWaitForPageIdleSecs = 5, forefront, exclude, onSkippedRequest, } = options;
66
69
  const waitForPageIdleMillis = waitForPageIdleSecs * 1000;
67
70
  const maxWaitForPageIdleMillis = maxWaitForPageIdleSecs * 1000;
71
+ const urlExcludePatternObjects = [];
68
72
  const urlPatternObjects = [];
73
+ if (exclude?.length) {
74
+ for (const excl of exclude) {
75
+ if (typeof excl === 'string' || 'glob' in excl) {
76
+ urlExcludePatternObjects.push(...constructGlobObjectsFromGlobs([excl]));
77
+ }
78
+ else if (excl instanceof RegExp || 'regexp' in excl) {
79
+ urlExcludePatternObjects.push(...constructRegExpObjectsFromRegExps([excl]));
80
+ }
81
+ }
82
+ }
69
83
  if (pseudoUrls?.length) {
70
- log.deprecated('`pseudoUrls` option is deprecated, use `globs` or `regexps` instead');
84
+ serviceLocator.getLogger().deprecated('`pseudoUrls` option is deprecated, use `globs` or `regexps` instead');
71
85
  urlPatternObjects.push(...constructRegExpObjectsFromPseudoUrls(pseudoUrls));
72
86
  }
73
87
  if (globs?.length) {
@@ -83,12 +97,21 @@ export async function enqueueLinksByClickingElements(options) {
83
97
  maxWaitForPageIdleMillis,
84
98
  clickOptions,
85
99
  });
86
- let requestOptions = createRequestOptions(interceptedRequests, options);
100
+ const requestOptions = createRequestOptions(interceptedRequests, options);
101
+ const skippedByFilters = [];
102
+ let filteredOptions = filterRequestOptionsByPatterns(requestOptions, urlPatternObjects.length > 0 ? urlPatternObjects : undefined, urlExcludePatternObjects, undefined, (url) => skippedByFilters.push(url));
103
+ if (onSkippedRequest && skippedByFilters.length > 0) {
104
+ await Promise.all(skippedByFilters.map(async (url) => onSkippedRequest({ url, reason: 'filters' })));
105
+ }
87
106
  if (transformRequestFunction) {
88
- requestOptions = requestOptions.map(transformRequestFunction).filter((r) => !!r);
107
+ const skippedByTransform = [];
108
+ filteredOptions = applyRequestTransform(filteredOptions, transformRequestFunction, (r) => skippedByTransform.push(r));
109
+ if (onSkippedRequest && skippedByTransform.length > 0) {
110
+ await Promise.all(skippedByTransform.map(async (r) => onSkippedRequest({ url: r.url, reason: 'transform' })));
111
+ }
89
112
  }
90
- const requests = createRequests(requestOptions, urlPatternObjects);
91
- const { addedRequests } = await requestQueue.addRequestsBatched(requests, { forefront });
113
+ const requests = filteredOptions.map((opts) => new CrawleeRequest(opts));
114
+ const { addedRequests } = await requestManager.addRequestsBatched(requests, { forefront });
92
115
  return { processedRequests: addedRequests, unprocessedRequests: [] };
93
116
  }
94
117
  /**
@@ -114,7 +137,7 @@ export async function clickElementsAndInterceptNavigationRequests(options) {
114
137
  await restoreHistoryNavigationAndSaveCapturedUrls(page, uniqueRequests);
115
138
  // browser.off(BrowserEmittedEvents.TargetCreated, onTargetCreated);
116
139
  page.off('framenavigated', onFrameNavigated);
117
- await context.unroute('*', onInterceptedRequest);
140
+ await context.unroute('**', onInterceptedRequest);
118
141
  const serializedRequests = Array.from(uniqueRequests);
119
142
  return serializedRequests.map((r) => JSON.parse(r));
120
143
  }
@@ -150,7 +173,9 @@ function createTargetCreatedHandler(requests) {
150
173
  await popup.close();
151
174
  }
152
175
  catch (err) {
153
- log.debug('enqueueLinksByClickingElements: Could not close spawned page.', { error: err.stack });
176
+ getLog().debug('enqueueLinksByClickingElements: Could not close spawned page.', {
177
+ error: err.stack,
178
+ });
154
179
  }
155
180
  };
156
181
  }
@@ -158,7 +183,16 @@ function createTargetCreatedHandler(requests) {
158
183
  * @ignore
159
184
  */
160
185
  function isTopFrameNavigationRequest(page, req) {
161
- return req.isNavigationRequest() && req.frame() === page.mainFrame();
186
+ try {
187
+ return req.isNavigationRequest() && req.frame() === page.mainFrame();
188
+ }
189
+ catch {
190
+ // `req.frame()` throws when the owning frame is unavailable - e.g. the request was
191
+ // issued by a service worker, or before/after its frame existed (see #3216). Such a
192
+ // request is not a top-frame navigation, so swallow the throw and let it pass through
193
+ // instead of crashing the route handler (which would leave the route unhandled).
194
+ return false;
195
+ }
162
196
  }
163
197
  /**
164
198
  * @ignore
@@ -223,7 +257,7 @@ function updateElementCssToEnableMouseClick(el, zIndex) {
223
257
  */
224
258
  export async function clickElements(page, selector, clickOptions) {
225
259
  const elementHandles = await page.$$(selector);
226
- log.debug(`enqueueLinksByClickingElements: There are ${elementHandles.length} elements to click.`);
260
+ getLog().debug(`enqueueLinksByClickingElements: There are ${elementHandles.length} elements to click.`);
227
261
  let clickedElementsCount = 0;
228
262
  let zIndex = STARTING_Z_INDEX;
229
263
  let shouldLogWarning = true;
@@ -236,15 +270,15 @@ export async function clickElements(page, selector, clickOptions) {
236
270
  catch (err) {
237
271
  const e = err;
238
272
  if (shouldLogWarning && e.stack.includes('is detached from document')) {
239
- log.warning(`An element with selector ${selector} that you're trying to click has been removed from the page. ` +
273
+ getLog().warning(`An element with selector ${selector} that you're trying to click has been removed from the page. ` +
240
274
  'This was probably caused by an earlier click which triggered some JavaScript on the page that caused it to change. ' +
241
275
  'If you\'re trying to enqueue pagination links, we suggest using the "next" button, if available and going one by one.');
242
276
  shouldLogWarning = false;
243
277
  }
244
- log.debug('enqueueLinksByClickingElements: Click failed.', { stack: e.stack });
278
+ getLog().debug('enqueueLinksByClickingElements: Click failed.', { stack: e.stack });
245
279
  }
246
280
  }
247
- log.debug(`enqueueLinksByClickingElements: Successfully clicked ${clickedElementsCount} elements out of ${elementHandles.length}`);
281
+ getLog().debug(`enqueueLinksByClickingElements: Successfully clicked ${clickedElementsCount} elements out of ${elementHandles.length}`);
248
282
  }
249
283
  /**
250
284
  * This function tracks whether any requests, frame navigations or targets were emitted
@@ -263,8 +297,6 @@ export async function clickElements(page, selector, clickOptions) {
263
297
  async function waitForPageIdle({ page, waitForPageIdleMillis, maxWaitForPageIdleMillis, }) {
264
298
  return new Promise((resolve) => {
265
299
  let timeout;
266
- let maxTimeout;
267
- page.on('popup', activityHandler);
268
300
  function activityHandler() {
269
301
  clearTimeout(timeout);
270
302
  timeout = setTimeout(() => {
@@ -273,7 +305,7 @@ async function waitForPageIdle({ page, waitForPageIdleMillis, maxWaitForPageIdle
273
305
  }, waitForPageIdleMillis);
274
306
  }
275
307
  function maxTimeoutHandler() {
276
- log.debug(`enqueueLinksByClickingElements: Page still showed activity after ${maxWaitForPageIdleMillis}ms. ` +
308
+ getLog().debug(`enqueueLinksByClickingElements: Page still showed activity after ${maxWaitForPageIdleMillis}ms. ` +
277
309
  'This is probably due to the website itself dispatching requests, but some links may also have been missed.');
278
310
  finish();
279
311
  }
@@ -281,7 +313,8 @@ async function waitForPageIdle({ page, waitForPageIdleMillis, maxWaitForPageIdle
281
313
  page.off('request', activityHandler).off('framenavigated', activityHandler).off('popup', activityHandler);
282
314
  resolve();
283
315
  }
284
- maxTimeout = setTimeout(maxTimeoutHandler, maxWaitForPageIdleMillis);
316
+ const maxTimeout = setTimeout(maxTimeoutHandler, maxWaitForPageIdleMillis);
317
+ page.on('popup', activityHandler);
285
318
  activityHandler(); // We call this once manually in case there would be no requests at all.
286
319
  page.on('request', activityHandler);
287
320
  page.on('framenavigated', activityHandler);
@@ -304,8 +337,7 @@ async function restoreHistoryNavigationAndSaveCapturedUrls(page, requests) {
304
337
  requests.add(JSON.stringify({ url }));
305
338
  }
306
339
  catch (err) {
307
- log.debug('enqueueLinksByClickingElements: Failed to ', { error: err.stack });
340
+ getLog().debug('enqueueLinksByClickingElements: Failed to ', { error: err.stack });
308
341
  }
309
342
  });
310
343
  }
311
- //# sourceMappingURL=click-elements.js.map
@@ -1,20 +1,19 @@
1
- import type { BrowserCrawlerOptions, BrowserCrawlingContext, BrowserHook, BrowserRequestHandler, GetUserDataFromRequest, RouterRoutes } from '@crawlee/browser';
2
- import { BrowserCrawler, Configuration } from '@crawlee/browser';
3
- import type { PlaywrightController, PlaywrightPlugin } from '@crawlee/browser-pool';
1
+ import type { BrowserCrawlerOptions, BrowserCrawlingContext, BrowserHook, GetUserDataFromRequest, RequestHandler, RouterHandler, RouterRoutes, RouteSchemas, RoutesFromSchemas } from '@crawlee/browser';
2
+ import { BrowserCrawler } from '@crawlee/browser';
3
+ import type { PlaywrightPlugin } from '@crawlee/browser-pool';
4
4
  import type { Dictionary } from '@crawlee/types';
5
5
  // @ts-ignore optional peer dependency or compatibility with es2022
6
- import type { LaunchOptions, Page, Response } from 'playwright';
6
+ import type { Download, LaunchOptions, Page, Response } from 'playwright';
7
+ import type { EnqueueLinksByClickingElementsOptions } from './enqueue-links/click-elements.js';
7
8
  import type { PlaywrightLaunchContext } from './playwright-launcher.js';
8
- import type { DirectNavigationOptions, PlaywrightContextUtils } from './utils/playwright-utils.js';
9
- export interface PlaywrightCrawlingContext<UserData extends Dictionary = Dictionary> extends BrowserCrawlingContext<PlaywrightCrawler, Page, Response, PlaywrightController, UserData>, PlaywrightContextUtils {
9
+ import type { BlockRequestsOptions, DirectNavigationOptions, HandleCloudflareChallengeOptions, InfiniteScrollOptions, InjectFileOptions, PlaywrightContextUtils, SaveSnapshotOptions } from './utils/playwright-utils.js';
10
+ export type PlaywrightGotoOptions = NonNullable<Parameters<Page['goto']>[1]>;
11
+ export interface PlaywrightCrawlingContext<UserData extends Dictionary = Dictionary> extends BrowserCrawlingContext<Page, Response, UserData, PlaywrightGotoOptions>, PlaywrightContextUtils {
10
12
  }
11
13
  // @ts-ignore optional peer dependency or compatibility with es2022
12
- export interface PlaywrightHook extends BrowserHook<PlaywrightCrawlingContext, PlaywrightGotoOptions> {
14
+ export interface PlaywrightHook extends BrowserHook<PlaywrightCrawlingContext> {
13
15
  }
14
- export interface PlaywrightRequestHandler extends BrowserRequestHandler<PlaywrightCrawlingContext> {
15
- }
16
- export type PlaywrightGotoOptions = Parameters<Page['goto']>[1];
17
- export interface PlaywrightCrawlerOptions extends BrowserCrawlerOptions<PlaywrightCrawlingContext, {
16
+ export interface PlaywrightCrawlerOptions<ContextExtension = Dictionary<never>, ExtendedContext extends PlaywrightCrawlingContext = PlaywrightCrawlingContext & ContextExtension> extends BrowserCrawlerOptions<Page, Response, PlaywrightCrawlingContext, ContextExtension, ExtendedContext, {
18
17
  browserPlugins: [PlaywrightPlugin];
19
18
  }> {
20
19
  /**
@@ -28,8 +27,6 @@ export interface PlaywrightCrawlerOptions extends BrowserCrawlerOptions<Playwrig
28
27
  * - `request` is an instance of the {@link Request} object with details about the URL to open, HTTP method etc.
29
28
  * - `page` is an instance of the `Playwright`
30
29
  * [`Page`](https://playwright.dev/docs/api/class-page)
31
- * - `browserController` is an instance of the
32
- * [`BrowserController`](https://github.com/apify/browser-pool#browsercontroller),
33
30
  * - `response` is an instance of the `Playwright`
34
31
  * [`Response`](https://playwright.dev/docs/api/class-response),
35
32
  * which is the main resource response as returned by `page.goto(request.url)`.
@@ -45,56 +42,28 @@ export interface PlaywrightCrawlerOptions extends BrowserCrawlerOptions<Playwrig
45
42
  * The exceptions are logged to the request using the
46
43
  * {@link Request.pushErrorMessage} function.
47
44
  */
48
- requestHandler?: PlaywrightRequestHandler;
49
- /**
50
- * Function that is called to process each request.
51
- *
52
- * The function receives the {@link PlaywrightCrawlingContext} as an argument, where:
53
- * - `request` is an instance of the {@link Request} object with details about the URL to open, HTTP method etc.
54
- * - `page` is an instance of the `Playwright`
55
- * [`Page`](https://playwright.dev/docs/api/class-page)
56
- * - `browserController` is an instance of the
57
- * [`BrowserController`](https://github.com/apify/browser-pool#browsercontroller),
58
- * - `response` is an instance of the `Playwright`
59
- * [`Response`](https://playwright.dev/docs/api/class-response),
60
- * which is the main resource response as returned by `page.goto(request.url)`.
61
- *
62
- * The function must return a promise, which is then awaited by the crawler.
63
- *
64
- * If the function throws an exception, the crawler will try to re-crawl the
65
- * request later, up to `option.maxRequestRetries` times.
66
- * If all the retries fail, the crawler calls the function
67
- * provided to the `failedRequestHandler` parameter.
68
- * To make this work, you should **always**
69
- * let your function throw exceptions rather than catch them.
70
- * The exceptions are logged to the request using the
71
- * {@link Request.pushErrorMessage} function.
72
- *
73
- * @deprecated `handlePageFunction` has been renamed to `requestHandler` and will be removed in a future version.
74
- * @ignore
75
- */
76
- handlePageFunction?: PlaywrightRequestHandler;
45
+ requestHandler?: RequestHandler<ExtendedContext>;
77
46
  /**
78
47
  * Async functions that are sequentially evaluated before the navigation. Good for setting additional cookies
79
- * or browser properties before navigation. The function accepts two parameters, `crawlingContext` and `gotoOptions`,
80
- * which are passed to the `page.goto()` function the crawler calls to navigate.
48
+ * or browser properties before navigation. The function receives the `crawlingContext`; the options object
49
+ * forwarded to `page.goto()` is available as `crawlingContext.gotoOptions` and can be mutated in place.
50
+ * A hook may optionally return a partial object whose properties are merged into the crawling context
51
+ * (e.g. to override context members for subsequent hooks and pipeline stages).
81
52
  * Example:
82
53
  * ```
83
54
  * preNavigationHooks: [
84
- * async (crawlingContext, gotoOptions) => {
85
- * const { page } = crawlingContext;
55
+ * async ({ page, gotoOptions }) => {
86
56
  * await page.evaluate((attr) => { window.foo = attr; }, 'bar');
57
+ * gotoOptions.timeout = 60_000;
87
58
  * },
88
59
  * ]
89
60
  * ```
90
- *
91
- * Modyfing `pageOptions` is supported only in Playwright incognito.
92
- * See {@link PrePageCreateHook}
93
61
  */
94
62
  preNavigationHooks?: PlaywrightHook[];
95
63
  /**
96
64
  * Async functions that are sequentially evaluated after the navigation. Good for checking if the navigation was successful.
97
- * The function accepts `crawlingContext` as the only parameter.
65
+ * The function accepts `crawlingContext` as the only parameter. A hook may optionally return a partial object
66
+ * whose properties are merged into the crawling context (e.g. to override `response` after solving a challenge).
98
67
  * Example:
99
68
  * ```
100
69
  * postNavigationHooks: [
@@ -120,13 +89,15 @@ export interface PlaywrightCrawlerOptions extends BrowserCrawlerOptions<Playwrig
120
89
  * If the target website doesn't need JavaScript, consider using {@link CheerioCrawler},
121
90
  * which downloads the pages using raw HTTP requests and is about 10x faster.
122
91
  *
123
- * The source URLs are represented using {@link Request} objects that are fed from
124
- * {@link RequestList} or {@link RequestQueue} instances provided by the {@link PlaywrightCrawlerOptions.requestList}
125
- * or {@link PlaywrightCrawlerOptions.requestQueue} constructor options, respectively.
92
+ * The source URLs are represented using {@link Request} objects that are fed from the
93
+ * {@link IRequestManager|request manager} provided via the {@link PlaywrightCrawlerOptions.requestManager|`requestManager`}
94
+ * constructor option (a {@link RequestQueue} is itself a request manager). To read from a read-only source such
95
+ * as a {@link RequestList} while still being able to enqueue new requests, combine it with a queue into a
96
+ * {@link RequestManagerTandem} via {@link IRequestLoader.toTandem|`requestLoader.toTandem()`} and pass the
97
+ * result as `requestManager`.
126
98
  *
127
- * If both {@link PlaywrightCrawlerOptions.requestList} and {@link PlaywrightCrawlerOptions.requestQueue} are used,
128
- * the instance first processes URLs from the {@link RequestList} and automatically enqueues all of them
129
- * to {@link RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.
99
+ * > The {@link PlaywrightCrawlerOptions.requestList|`requestList`} and {@link PlaywrightCrawlerOptions.requestQueue|`requestQueue`}
100
+ * > options are deprecated; they are still accepted and folded into a single `requestManager` for back-compat.
130
101
  *
131
102
  * The crawler finishes when there are no more {@link Request} objects to crawl.
132
103
  *
@@ -172,16 +143,18 @@ export interface PlaywrightCrawlerOptions extends BrowserCrawlerOptions<Playwrig
172
143
  * ```
173
144
  * @category Crawlers
174
145
  */
175
- export declare class PlaywrightCrawler extends BrowserCrawler<{
146
+ export declare class PlaywrightCrawler<ContextExtension = Dictionary<never>, ExtendedContext extends PlaywrightCrawlingContext = PlaywrightCrawlingContext & ContextExtension> extends BrowserCrawler<Page, Response, {
176
147
  browserPlugins: [PlaywrightPlugin];
177
- }, LaunchOptions, PlaywrightCrawlingContext> {
178
- private readonly options;
179
- readonly config: Configuration;
148
+ }, LaunchOptions, PlaywrightCrawlingContext, ContextExtension, ExtendedContext> {
180
149
  protected static optionsShape: {
181
150
  // @ts-ignore optional peer dependency or compatibility with es2022
182
151
  browserPoolOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
183
152
  // @ts-ignore optional peer dependency or compatibility with es2022
184
153
  launcher: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
154
+ // @ts-ignore optional peer dependency or compatibility with es2022
155
+ ignoreIframes: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
156
+ // @ts-ignore optional peer dependency or compatibility with es2022
157
+ ignoreShadowRoots: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
185
158
  // @ts-ignore optional peer dependency or compatibility with es2022
186
159
  navigationTimeoutSecs: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
187
160
  // @ts-ignore optional peer dependency or compatibility with es2022
@@ -193,17 +166,17 @@ export declare class PlaywrightCrawler extends BrowserCrawler<{
193
166
  // @ts-ignore optional peer dependency or compatibility with es2022
194
167
  headless: import("ow").AnyPredicate<string | boolean>;
195
168
  // @ts-ignore optional peer dependency or compatibility with es2022
196
- sessionPoolOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
169
+ browserPool: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
197
170
  // @ts-ignore optional peer dependency or compatibility with es2022
198
- persistCookiesPerSession: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
171
+ remoteBrowser: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
199
172
  // @ts-ignore optional peer dependency or compatibility with es2022
200
- useSessionPool: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
173
+ saveResponseCookies: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
201
174
  // @ts-ignore optional peer dependency or compatibility with es2022
202
175
  proxyConfiguration: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
203
176
  // @ts-ignore optional peer dependency or compatibility with es2022
204
- ignoreShadowRoots: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
177
+ contextPipelineBuilder: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
205
178
  // @ts-ignore optional peer dependency or compatibility with es2022
206
- ignoreIframes: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
179
+ extendContext: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
207
180
  // @ts-ignore optional peer dependency or compatibility with es2022
208
181
  requestList: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
209
182
  // @ts-ignore optional peer dependency or compatibility with es2022
@@ -220,24 +193,40 @@ export declare class PlaywrightCrawler extends BrowserCrawler<{
220
193
  maxRequestRetries: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
221
194
  // @ts-ignore optional peer dependency or compatibility with es2022
222
195
  sameDomainDelaySecs: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
223
- // @ts-ignore optional peer dependency or compatibility with es2022
224
- maxSessionRotations: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
225
196
  // @ts-ignore optional peer dependency or compatibility with es2022
226
197
  maxRequestsPerCrawl: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
198
+ // @ts-ignore optional peer dependency or compatibility with es2022
199
+ maxCrawlDepth: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
227
200
  // @ts-ignore optional peer dependency or compatibility with es2022
228
201
  autoscaledPoolOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
202
+ // @ts-ignore optional peer dependency or compatibility with es2022
203
+ sessionPool: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
229
204
  // @ts-ignore optional peer dependency or compatibility with es2022
230
205
  statusMessageLoggingInterval: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
231
206
  // @ts-ignore optional peer dependency or compatibility with es2022
232
207
  statusMessageCallback: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
208
+ // @ts-ignore optional peer dependency or compatibility with es2022
209
+ additionalHttpErrorStatusCodes: import("ow").ArrayPredicate<number>;
210
+ // @ts-ignore optional peer dependency or compatibility with es2022
211
+ ignoreHttpErrorStatusCodes: import("ow").ArrayPredicate<number>;
212
+ // @ts-ignore optional peer dependency or compatibility with es2022
213
+ blockedStatusCodes: import("ow").ArrayPredicate<number>;
233
214
  // @ts-ignore optional peer dependency or compatibility with es2022
234
215
  retryOnBlocked: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
235
216
  // @ts-ignore optional peer dependency or compatibility with es2022
236
- respectRobotsTxtFile: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
217
+ respectRobotsTxtFile: import("ow").AnyPredicate<boolean | object>;
237
218
  // @ts-ignore optional peer dependency or compatibility with es2022
238
219
  onSkippedRequest: import("ow").Predicate<Function> & import("ow").BasePredicate<Function | undefined>;
239
220
  // @ts-ignore optional peer dependency or compatibility with es2022
240
221
  httpClient: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
222
+ // @ts-ignore optional peer dependency or compatibility with es2022
223
+ configuration: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
224
+ // @ts-ignore optional peer dependency or compatibility with es2022
225
+ storageBackend: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
226
+ // @ts-ignore optional peer dependency or compatibility with es2022
227
+ eventManager: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
228
+ // @ts-ignore optional peer dependency or compatibility with es2022
229
+ logger: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
241
230
  // @ts-ignore optional peer dependency or compatibility with es2022
242
231
  minConcurrency: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
243
232
  // @ts-ignore optional peer dependency or compatibility with es2022
@@ -246,20 +235,50 @@ export declare class PlaywrightCrawler extends BrowserCrawler<{
246
235
  maxRequestsPerMinute: import("ow").NumberPredicate & import("ow").BasePredicate<number | undefined>;
247
236
  // @ts-ignore optional peer dependency or compatibility with es2022
248
237
  keepAlive: import("ow").BooleanPredicate & import("ow").BasePredicate<boolean | undefined>;
249
- // @ts-ignore optional peer dependency or compatibility with es2022
250
- log: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
251
- // @ts-ignore optional peer dependency or compatibility with es2022
252
- experiments: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
253
238
  // @ts-ignore optional peer dependency or compatibility with es2022
254
239
  statisticsOptions: import("ow").ObjectPredicate<object> & import("ow").BasePredicate<object | undefined>;
240
+ // @ts-ignore optional peer dependency or compatibility with es2022
241
+ id: import("ow").StringPredicate & import("ow").BasePredicate<string | undefined>;
255
242
  };
256
243
  /**
257
244
  * All `PlaywrightCrawler` parameters are passed via an options object.
258
245
  */
259
- constructor(options?: PlaywrightCrawlerOptions, config?: Configuration);
260
- protected _runRequestHandler(context: PlaywrightCrawlingContext): Promise<void>;
246
+ constructor(options?: PlaywrightCrawlerOptions<ExtendedContext>);
247
+ // @ts-ignore optional peer dependency or compatibility with es2022
248
+ protected buildContextPipeline(): import("@crawlee/browser").ContextPipeline<import("@crawlee/browser").CrawlingContext<Dictionary>, BrowserCrawlingContext<Page, Response, Dictionary, Dictionary> & {
249
+ injectFile: (filePath: string, options?: InjectFileOptions) => Promise<unknown>;
250
+ injectJQuery: () => Promise<void>;
251
+ blockRequests: (options?: BlockRequestsOptions) => Promise<void>;
252
+ waitForSelector: (selector: string, timeoutMs?: number) => Promise<void>;
253
+ // @ts-ignore optional peer dependency or compatibility with es2022
254
+ parseWithCheerio: (selector?: string, timeoutMs?: number) => Promise<import("@crawlee/browser").CheerioAPI>;
255
+ infiniteScroll: (options?: InfiniteScrollOptions) => Promise<void>;
256
+ listDownloads: () => Promise<Download[]>;
257
+ saveSnapshot: (options?: SaveSnapshotOptions) => Promise<void>;
258
+ // @ts-ignore optional peer dependency or compatibility with es2022
259
+ enqueueLinksByClickingElements: (options: Omit<EnqueueLinksByClickingElementsOptions, "page" | "requestManager">) => Promise<import("@crawlee/types").BatchAddRequestsResult>;
260
+ // @ts-ignore optional peer dependency or compatibility with es2022
261
+ compileScript: (scriptString: string, ctx?: Dictionary) => import("./utils/playwright-utils.js").CompiledScriptFunction;
262
+ closeCookieModals: () => Promise<void>;
263
+ handleCloudflareChallenge: (options?: HandleCloudflareChallengeOptions) => Promise<Response | undefined>;
264
+ }>;
261
265
  protected _navigationHandler(crawlingContext: PlaywrightCrawlingContext, gotoOptions: DirectNavigationOptions): Promise<Response | null>;
266
+ private enhanceContext;
262
267
  }
268
+ /**
269
+ * Returns a `postNavigationHooks`-ready hook that runs {@link PlaywrightContextUtils.handleCloudflareChallenge}
270
+ * and propagates the post-challenge {@link Response} back into the crawling context via its return value.
271
+ *
272
+ * **Example usage**
273
+ * ```ts
274
+ * import { PlaywrightCrawler, handleCloudflareChallengeHook } from 'crawlee';
275
+ *
276
+ * const crawler = new PlaywrightCrawler({
277
+ * postNavigationHooks: [handleCloudflareChallengeHook()],
278
+ * });
279
+ * ```
280
+ */
281
+ export declare function handleCloudflareChallengeHook(options?: HandleCloudflareChallengeOptions): PlaywrightHook;
263
282
  /**
264
283
  * Creates new {@link Router} instance that works based on request labels.
265
284
  * This instance can then serve as a `requestHandler` of your {@link PlaywrightCrawler}.
@@ -284,6 +303,6 @@ export declare class PlaywrightCrawler extends BrowserCrawler<{
284
303
  * await crawler.run();
285
304
  * ```
286
305
  */
287
- // @ts-ignore optional peer dependency or compatibility with es2022
288
- export declare function createPlaywrightRouter<Context extends PlaywrightCrawlingContext = PlaywrightCrawlingContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, UserData>): import("@crawlee/browser").RouterHandler<Context>;
289
- //# sourceMappingURL=playwright-crawler.d.ts.map
306
+ export declare function createPlaywrightRouter<Context extends PlaywrightCrawlingContext = PlaywrightCrawlingContext, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<Context['request']>>>(routes?: RouterRoutes<Context, Routes>): RouterHandler<Context, Routes>;
307
+ export declare function createPlaywrightRouter<Context extends PlaywrightCrawlingContext = PlaywrightCrawlingContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, Record<string, UserData>>): RouterHandler<Context, Record<string, UserData>>;
308
+ export declare function createPlaywrightRouter<Context extends PlaywrightCrawlingContext = PlaywrightCrawlingContext, const Schemas extends RouteSchemas = RouteSchemas>(schemas: Schemas): RouterHandler<Context, RoutesFromSchemas<Schemas>>;