@crawlee/playwright 4.0.0-beta.33 → 4.0.0-beta.330
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.
- package/README.md +15 -11
- package/index.d.ts +4 -3
- package/index.js +2 -2
- package/internals/adaptive-playwright-crawler.d.ts +156 -82
- package/internals/adaptive-playwright-crawler.js +561 -300
- package/internals/enqueue-links/click-elements.d.ts +21 -58
- package/internals/enqueue-links/click-elements.js +48 -61
- package/internals/playwright-browser-pool.d.ts +55 -0
- package/internals/playwright-browser-pool.js +34 -0
- package/internals/playwright-crawler.d.ts +179 -171
- package/internals/playwright-crawler.js +121 -77
- package/internals/playwright-launcher.d.ts +30 -22
- package/internals/playwright-launcher.js +24 -18
- package/internals/utils/playwright-utils.d.ts +66 -54
- package/internals/utils/playwright-utils.js +128 -137
- package/internals/utils/rendering-type-prediction.d.ts +42 -13
- package/internals/utils/rendering-type-prediction.js +83 -50
- package/package.json +20 -23
- package/index.d.ts.map +0 -1
- package/index.js.map +0 -1
- package/internals/adaptive-playwright-crawler.d.ts.map +0 -1
- package/internals/adaptive-playwright-crawler.js.map +0 -1
- package/internals/enqueue-links/click-elements.d.ts.map +0 -1
- package/internals/enqueue-links/click-elements.js.map +0 -1
- package/internals/playwright-crawler.d.ts.map +0 -1
- package/internals/playwright-crawler.js.map +0 -1
- package/internals/playwright-launcher.d.ts.map +0 -1
- package/internals/playwright-launcher.js.map +0 -1
- package/internals/utils/playwright-utils.d.ts.map +0 -1
- package/internals/utils/playwright-utils.js.map +0 -1
- package/internals/utils/rendering-type-prediction.d.ts.map +0 -1
- package/internals/utils/rendering-type-prediction.js.map +0 -1
|
@@ -17,14 +17,14 @@
|
|
|
17
17
|
* ```
|
|
18
18
|
* @module playwrightUtils
|
|
19
19
|
*/
|
|
20
|
-
import { Configuration, type Request
|
|
21
|
-
import type { BatchAddRequestsResult } from '@crawlee/types';
|
|
22
|
-
import {
|
|
20
|
+
import { Configuration, type Request } from '@crawlee/browser';
|
|
21
|
+
import type { BatchAddRequestsResult, Dictionary } from '@crawlee/types';
|
|
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
|
-
import type { Page, Response } from 'playwright';
|
|
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.
|
|
@@ -265,9 +265,9 @@ export interface SaveSnapshotOptions {
|
|
|
265
265
|
keyValueStoreName?: string | null;
|
|
266
266
|
/**
|
|
267
267
|
* Configuration of the crawler that will be used to save the snapshot.
|
|
268
|
-
* @default Configuration.
|
|
268
|
+
* @default Configuration.getGlobalConfiguration()
|
|
269
269
|
*/
|
|
270
|
-
|
|
270
|
+
configuration?: Configuration;
|
|
271
271
|
}
|
|
272
272
|
/**
|
|
273
273
|
* Saves a full screenshot and HTML of the current page into a Key-Value store.
|
|
@@ -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<
|
|
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;
|
|
@@ -318,24 +317,31 @@ export interface HandleCloudflareChallengeOptions {
|
|
|
318
317
|
* result in a SessionError which will be automatically retried, so only successful requests will get
|
|
319
318
|
* into the `requestHandler`.
|
|
320
319
|
*
|
|
320
|
+
* On a successfully solved challenge the page is reloaded and the new {@link Response} is returned, so
|
|
321
|
+
* it can be propagated back to the crawling context via a hook return value (see
|
|
322
|
+
* {@link handleCloudflareChallengeHook}). Thanks to that, the 403 status of the challenge page does not
|
|
323
|
+
* need to be removed from `blockedStatusCodes` - a solved challenge replaces the response before the
|
|
324
|
+
* blocked-status check runs, and an unsolved one is retried with a fresh session.
|
|
325
|
+
*
|
|
321
326
|
* Works best with camoufox.
|
|
322
327
|
*
|
|
323
328
|
* **Example usage**
|
|
324
329
|
* ```ts
|
|
325
330
|
* postNavigationHooks: [
|
|
326
|
-
* async (
|
|
327
|
-
* await handleCloudflareChallenge();
|
|
331
|
+
* async (context) => {
|
|
332
|
+
* const response = await context.handleCloudflareChallenge();
|
|
333
|
+
* // `{ response: undefined }` would replace the navigation response and skip the blocked-status check
|
|
334
|
+
* return response && { response };
|
|
328
335
|
* },
|
|
329
336
|
* ],
|
|
330
337
|
* ```
|
|
331
338
|
*
|
|
332
339
|
* @param page Playwright [`Page`](https://playwright.dev/docs/api/class-page) object
|
|
333
340
|
* @param url current URL for request identification, only used for logging
|
|
334
|
-
* @param [session] current session object
|
|
335
341
|
* @param [options]
|
|
342
|
+
* @param [response] navigation response, used to poll for late-rendered challenge markup when it signals a likely challenge
|
|
336
343
|
*/
|
|
337
|
-
declare function handleCloudflareChallenge(page: Page, url: string,
|
|
338
|
-
/** @internal */
|
|
344
|
+
export declare function handleCloudflareChallenge(page: Page, url: string, options?: HandleCloudflareChallengeOptions, response?: Response): Promise<Response | undefined>;
|
|
339
345
|
export interface PlaywrightContextUtils {
|
|
340
346
|
/**
|
|
341
347
|
* Injects a JavaScript file into current `page`.
|
|
@@ -422,6 +428,15 @@ export interface PlaywrightContextUtils {
|
|
|
422
428
|
* ```
|
|
423
429
|
*/
|
|
424
430
|
waitForSelector(selector: string, timeoutMs?: number): Promise<void>;
|
|
431
|
+
/**
|
|
432
|
+
* Like {@link PlaywrightContextUtils.waitForSelector|`waitForSelector`}, but returns the matched elements
|
|
433
|
+
* as a Cheerio object. Throws when nothing matches.
|
|
434
|
+
*/
|
|
435
|
+
querySelectorAll(selector: string, timeoutMs?: number): Promise<Cheerio<AnyNode>>;
|
|
436
|
+
/**
|
|
437
|
+
* Like {@link PlaywrightContextUtils.querySelectorAll|`querySelectorAll`}, but returns only the first match.
|
|
438
|
+
*/
|
|
439
|
+
querySelectorOne(selector: string, timeoutMs?: number): Promise<Cheerio<AnyNode>>;
|
|
425
440
|
/**
|
|
426
441
|
* Returns Cheerio handle for `page.content()`, allowing to work with the data same way as with {@link CheerioCrawler}.
|
|
427
442
|
* When provided with the `selector` argument, it waits for it to be available first.
|
|
@@ -434,7 +449,7 @@ export interface PlaywrightContextUtils {
|
|
|
434
449
|
* });
|
|
435
450
|
* ```
|
|
436
451
|
*/
|
|
437
|
-
parseWithCheerio(selector?: string, timeoutMs?: number): Promise<
|
|
452
|
+
parseWithCheerio(selector?: string, timeoutMs?: number): Promise<CheerioAPI>;
|
|
438
453
|
/**
|
|
439
454
|
* Scrolls to the bottom of a page, or until it times out.
|
|
440
455
|
* Loads dynamic content when it hits the bottom of a page, and then continues scrolling.
|
|
@@ -454,8 +469,7 @@ export interface PlaywrightContextUtils {
|
|
|
454
469
|
* in `href` elements, but rather navigations are triggered in click handlers.
|
|
455
470
|
* If you're looking to find URLs in `href` attributes of the page, see {@link enqueueLinks}.
|
|
456
471
|
*
|
|
457
|
-
* Optionally, the function allows you to filter the target links' URLs using an array of
|
|
458
|
-
* and override settings of the enqueued {@link Request} objects.
|
|
472
|
+
* Optionally, the function allows you to filter the target links' URLs using an array of glob or regexp patterns.
|
|
459
473
|
*
|
|
460
474
|
* **IMPORTANT**: To be able to do this, this function uses various mutations on the page,
|
|
461
475
|
* such as changing the Z-index of elements being clicked and their visibility. Therefore,
|
|
@@ -476,9 +490,9 @@ export interface PlaywrightContextUtils {
|
|
|
476
490
|
* async requestHandler({ enqueueLinksByClickingElements }) {
|
|
477
491
|
* await enqueueLinksByClickingElements({
|
|
478
492
|
* selector: 'a.product-detail',
|
|
479
|
-
*
|
|
480
|
-
* 'https://www.example.com/handbags/**'
|
|
481
|
-
* 'https://www.example.com/purses/**'
|
|
493
|
+
* include: [
|
|
494
|
+
* 'https://www.example.com/handbags/**',
|
|
495
|
+
* 'https://www.example.com/purses/**',
|
|
482
496
|
* ],
|
|
483
497
|
* });
|
|
484
498
|
* });
|
|
@@ -486,7 +500,7 @@ export interface PlaywrightContextUtils {
|
|
|
486
500
|
*
|
|
487
501
|
* @returns Promise that resolves to {@link BatchAddRequestsResult} object.
|
|
488
502
|
*/
|
|
489
|
-
enqueueLinksByClickingElements(options: Omit<EnqueueLinksByClickingElementsOptions, 'page' | '
|
|
503
|
+
enqueueLinksByClickingElements(options: Omit<EnqueueLinksByClickingElementsOptions, 'page' | 'requestManager'>): Promise<BatchAddRequestsResult>;
|
|
490
504
|
/**
|
|
491
505
|
* Compiles a Playwright script into an async function that may be executed at any time
|
|
492
506
|
* by providing it with the following object:
|
|
@@ -514,19 +528,6 @@ export interface PlaywrightContextUtils {
|
|
|
514
528
|
* secured copies beforehand.
|
|
515
529
|
*/
|
|
516
530
|
compileScript(scriptString: string, ctx?: Dictionary): CompiledScriptFunction;
|
|
517
|
-
/**
|
|
518
|
-
* Tries to close cookie consent modals on the page. Based on the I Don't Care About Cookies browser extension.
|
|
519
|
-
*
|
|
520
|
-
* Note that this method requires the idcac-playwright package to be installed.
|
|
521
|
-
* Crawlee does not include it by default due to licensing issues.
|
|
522
|
-
*
|
|
523
|
-
* To use this method, please install the package manually by running:
|
|
524
|
-
*
|
|
525
|
-
* ```bash
|
|
526
|
-
* npm install idcac-playwright
|
|
527
|
-
* ```
|
|
528
|
-
*/
|
|
529
|
-
closeCookieModals(): Promise<void>;
|
|
530
531
|
/**
|
|
531
532
|
* This helper tries to solve the Cloudflare challenge automatically by clicking on the checkbox.
|
|
532
533
|
* It will try to detect the Cloudflare page, click on the checkbox, and wait for 10 seconds (configurable
|
|
@@ -534,35 +535,46 @@ export interface PlaywrightContextUtils {
|
|
|
534
535
|
* result in a SessionError which will be automatically retried, so only successful requests will get
|
|
535
536
|
* into the `requestHandler`.
|
|
536
537
|
*
|
|
537
|
-
*
|
|
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.
|
|
538
541
|
*
|
|
539
542
|
* **Example usage**
|
|
540
543
|
* ```ts
|
|
541
544
|
* postNavigationHooks: [
|
|
542
|
-
* async (
|
|
543
|
-
* await handleCloudflareChallenge();
|
|
545
|
+
* async (context) => {
|
|
546
|
+
* const response = await context.handleCloudflareChallenge();
|
|
547
|
+
* // `{ response: undefined }` would replace the navigation response and skip the blocked-status check
|
|
548
|
+
* return response && { response };
|
|
544
549
|
* },
|
|
545
550
|
* ],
|
|
546
551
|
* ```
|
|
547
552
|
*
|
|
548
553
|
* @param [options]
|
|
549
554
|
*/
|
|
550
|
-
handleCloudflareChallenge(options?: HandleCloudflareChallengeOptions): Promise<
|
|
555
|
+
handleCloudflareChallenge(options?: HandleCloudflareChallengeOptions): Promise<Response | undefined>;
|
|
556
|
+
/**
|
|
557
|
+
* Returns the list of {@link https://playwright.dev/docs/api/class-download | Download} objects
|
|
558
|
+
* collected during the current page navigation and request handler.
|
|
559
|
+
*
|
|
560
|
+
* Useful for accessing files that the page downloads automatically.
|
|
561
|
+
* For most use cases, prefer re-enqueueing the URL to {@link FileDownload}.
|
|
562
|
+
* Use this only when direct access to the Playwright `Download` object is required.
|
|
563
|
+
*
|
|
564
|
+
* **Example usage**
|
|
565
|
+
* ```ts
|
|
566
|
+
* requestHandler: async ({ listDownloads }) => {
|
|
567
|
+
* for (const download of await listDownloads()) {
|
|
568
|
+
* try {
|
|
569
|
+
* const stream = await download.createReadStream();
|
|
570
|
+
* // stream to storage...
|
|
571
|
+
* } catch {
|
|
572
|
+
* // download failed or was cancelled
|
|
573
|
+
* }
|
|
574
|
+
* }
|
|
575
|
+
* },
|
|
576
|
+
* ```
|
|
577
|
+
*/
|
|
578
|
+
listDownloads(): Promise<Download[]>;
|
|
551
579
|
}
|
|
552
580
|
export { enqueueLinksByClickingElements };
|
|
553
|
-
/** @internal */
|
|
554
|
-
export declare const playwrightUtils: {
|
|
555
|
-
injectFile: typeof injectFile;
|
|
556
|
-
injectJQuery: typeof injectJQuery;
|
|
557
|
-
gotoExtended: typeof gotoExtended;
|
|
558
|
-
blockRequests: typeof blockRequests;
|
|
559
|
-
enqueueLinksByClickingElements: typeof enqueueLinksByClickingElements;
|
|
560
|
-
parseWithCheerio: typeof parseWithCheerio;
|
|
561
|
-
infiniteScroll: typeof infiniteScroll;
|
|
562
|
-
saveSnapshot: typeof saveSnapshot;
|
|
563
|
-
compileScript: typeof compileScript;
|
|
564
|
-
closeCookieModals: typeof closeCookieModals;
|
|
565
|
-
RenderingTypePredictor: typeof RenderingTypePredictor;
|
|
566
|
-
handleCloudflareChallenge: typeof handleCloudflareChallenge;
|
|
567
|
-
};
|
|
568
|
-
//# sourceMappingURL=playwright-utils.d.ts.map
|
|
@@ -20,18 +20,47 @@
|
|
|
20
20
|
import { readFile } from 'node:fs/promises';
|
|
21
21
|
import { createRequire } from 'node:module';
|
|
22
22
|
import vm from 'node:vm';
|
|
23
|
-
import { Configuration, KeyValueStore, serviceLocator, SessionError, validators
|
|
24
|
-
import {
|
|
25
|
-
import
|
|
26
|
-
import
|
|
23
|
+
import { Configuration, KeyValueStore, serviceLocator, SessionError, validators } from '@crawlee/browser';
|
|
24
|
+
import { sleep } from '@crawlee/utils';
|
|
25
|
+
import { expandShadowRoots, parseArgument, schemas, snapshotPageWithIframes } from '@crawlee/utils/internal';
|
|
26
|
+
import { z } from 'zod';
|
|
27
27
|
import { LruCache } from '@apify/datastructures';
|
|
28
28
|
import { enqueueLinksByClickingElements } from '../enqueue-links/click-elements.js';
|
|
29
|
-
import { RenderingTypePredictor } from './rendering-type-prediction.js';
|
|
30
29
|
const getLog = () => serviceLocator.getChildLog('Playwright Utils');
|
|
31
30
|
const require = createRequire(import.meta.url);
|
|
32
31
|
const jqueryPath = require.resolve('jquery');
|
|
33
32
|
const MAX_INJECT_FILE_CACHE_SIZE = 10;
|
|
34
33
|
const DEFAULT_BLOCK_REQUEST_URL_PATTERNS = ['.css', '.jpg', '.jpeg', '.png', '.svg', '.gif', '.woff', '.pdf', '.zip'];
|
|
34
|
+
const filePathSchema = z.string();
|
|
35
|
+
const injectFileOptionsSchema = z.strictObject({
|
|
36
|
+
surviveNavigations: z.boolean().optional(),
|
|
37
|
+
});
|
|
38
|
+
const gotoExtendedRequestSchema = z.looseObject({
|
|
39
|
+
url: z.url(),
|
|
40
|
+
method: z.string().optional(),
|
|
41
|
+
headers: schemas.anyObject.optional(),
|
|
42
|
+
payload: z.union([z.string(), z.instanceof(Uint8Array)]).optional(),
|
|
43
|
+
});
|
|
44
|
+
const blockRequestsOptionsSchema = z.strictObject({
|
|
45
|
+
urlPatterns: schemas.arrayOf(z.string(), 'strings').default(DEFAULT_BLOCK_REQUEST_URL_PATTERNS),
|
|
46
|
+
extraUrlPatterns: schemas.arrayOf(z.string(), 'strings').default(() => []),
|
|
47
|
+
});
|
|
48
|
+
const infiniteScrollOptionsSchema = z.strictObject({
|
|
49
|
+
timeoutSecs: schemas.anyNumber.default(0),
|
|
50
|
+
maxScrollHeight: schemas.anyNumber.default(0),
|
|
51
|
+
waitForSecs: schemas.anyNumber.default(4),
|
|
52
|
+
scrollDownAndUp: z.boolean().default(false),
|
|
53
|
+
buttonSelector: z.string().optional(),
|
|
54
|
+
stopScrollCallback: schemas.anyFunction.optional(),
|
|
55
|
+
});
|
|
56
|
+
const saveSnapshotOptionsSchema = z.strictObject({
|
|
57
|
+
key: z.string().min(1).default('SNAPSHOT'),
|
|
58
|
+
screenshotQuality: schemas.anyNumber.default(50),
|
|
59
|
+
saveScreenshot: z.boolean().default(true),
|
|
60
|
+
saveHtml: z.boolean().default(true),
|
|
61
|
+
keyValueStoreName: z.string().optional(),
|
|
62
|
+
configuration: schemas.anyObject.optional(),
|
|
63
|
+
});
|
|
35
64
|
/**
|
|
36
65
|
* Cache contents of previously injected files to limit file system access.
|
|
37
66
|
*/
|
|
@@ -48,18 +77,16 @@ const injectedFilesCache = new LruCache({ maxLength: MAX_INJECT_FILE_CACHE_SIZE
|
|
|
48
77
|
* @param [options]
|
|
49
78
|
*/
|
|
50
79
|
export async function injectFile(page, filePath, options = {}) {
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
surviveNavigations: ow.optional.boolean,
|
|
55
|
-
}));
|
|
80
|
+
parseArgument(page, validators.browserPage);
|
|
81
|
+
parseArgument(filePath, filePathSchema);
|
|
82
|
+
const { surviveNavigations } = parseArgument(options, injectFileOptionsSchema);
|
|
56
83
|
let contents = injectedFilesCache.get(filePath);
|
|
57
84
|
if (!contents) {
|
|
58
85
|
contents = await readFile(filePath, 'utf8');
|
|
59
86
|
injectedFilesCache.add(filePath, contents);
|
|
60
87
|
}
|
|
61
88
|
const evalP = page.evaluate(contents);
|
|
62
|
-
if (
|
|
89
|
+
if (surviveNavigations) {
|
|
63
90
|
page.on('framenavigated', async () => page
|
|
64
91
|
.evaluate(contents)
|
|
65
92
|
.catch((error) => getLog().warning('An error occurred during the script injection!', { error })));
|
|
@@ -93,7 +120,7 @@ export async function injectFile(page, filePath, options = {}) {
|
|
|
93
120
|
* @param [options.surviveNavigations] Opt-out option to disable the JQuery reinjection after navigation.
|
|
94
121
|
*/
|
|
95
122
|
export async function injectJQuery(page, options) {
|
|
96
|
-
|
|
123
|
+
parseArgument(page, validators.browserPage);
|
|
97
124
|
return injectFile(page, jqueryPath, { surviveNavigations: options?.surviveNavigations ?? true });
|
|
98
125
|
}
|
|
99
126
|
/**
|
|
@@ -109,17 +136,12 @@ export async function injectJQuery(page, options) {
|
|
|
109
136
|
* @param [gotoOptions] Custom options for `page.goto()`.
|
|
110
137
|
*/
|
|
111
138
|
export async function gotoExtended(page, request, gotoOptions = {}) {
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
method: ow.optional.string,
|
|
116
|
-
headers: ow.optional.object,
|
|
117
|
-
payload: ow.optional.any(ow.string, ow.uint8Array),
|
|
118
|
-
}));
|
|
119
|
-
ow(gotoOptions, ow.object);
|
|
139
|
+
parseArgument(page, validators.browserPage);
|
|
140
|
+
parseArgument(request, gotoExtendedRequestSchema);
|
|
141
|
+
parseArgument(gotoOptions, schemas.anyObject);
|
|
120
142
|
const { url, method, headers, payload } = request;
|
|
121
143
|
const isEmpty = (o) => !o || Object.keys(o).length === 0;
|
|
122
|
-
if (method !== 'GET' || payload
|
|
144
|
+
if (method !== 'GET' || payload) {
|
|
123
145
|
// This is not deprecated, we use it to log only once.
|
|
124
146
|
getLog().deprecated('Using other request methods than GET, rewriting headers and adding payloads has a high impact on performance ' +
|
|
125
147
|
'in recent versions of Playwright. Use only when necessary.');
|
|
@@ -148,6 +170,9 @@ export async function gotoExtended(page, request, gotoOptions = {}) {
|
|
|
148
170
|
};
|
|
149
171
|
await page.route('**/*', interceptRequestHandler);
|
|
150
172
|
}
|
|
173
|
+
else if (!isEmpty(headers)) {
|
|
174
|
+
await page.setExtraHTTPHeaders(headers);
|
|
175
|
+
}
|
|
151
176
|
return page.goto(url, gotoOptions);
|
|
152
177
|
}
|
|
153
178
|
/**
|
|
@@ -198,12 +223,8 @@ export async function gotoExtended(page, request, gotoOptions = {}) {
|
|
|
198
223
|
* @param [options]
|
|
199
224
|
*/
|
|
200
225
|
export async function blockRequests(page, options = {}) {
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
urlPatterns: ow.optional.array.ofType(ow.string),
|
|
204
|
-
extraUrlPatterns: ow.optional.array.ofType(ow.string),
|
|
205
|
-
}));
|
|
206
|
-
const { urlPatterns = DEFAULT_BLOCK_REQUEST_URL_PATTERNS, extraUrlPatterns = [] } = options;
|
|
226
|
+
parseArgument(page, validators.browserPage);
|
|
227
|
+
const { urlPatterns, extraUrlPatterns } = parseArgument(options, blockRequestsOptionsSchema);
|
|
207
228
|
const patternsToBlock = [...urlPatterns, ...extraUrlPatterns];
|
|
208
229
|
try {
|
|
209
230
|
const client = await page.context().newCDPSession(page);
|
|
@@ -261,16 +282,8 @@ export function compileScript(scriptString, context = Object.create(null)) {
|
|
|
261
282
|
* @param [options]
|
|
262
283
|
*/
|
|
263
284
|
export async function infiniteScroll(page, options = {}) {
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
timeoutSecs: ow.optional.number,
|
|
267
|
-
maxScrollHeight: ow.optional.number,
|
|
268
|
-
waitForSecs: ow.optional.number,
|
|
269
|
-
scrollDownAndUp: ow.optional.boolean,
|
|
270
|
-
buttonSelector: ow.optional.string,
|
|
271
|
-
stopScrollCallback: ow.optional.function,
|
|
272
|
-
}));
|
|
273
|
-
const { timeoutSecs = 0, maxScrollHeight = 0, waitForSecs = 4, scrollDownAndUp = false, buttonSelector, stopScrollCallback, } = options;
|
|
285
|
+
parseArgument(page, validators.browserPage);
|
|
286
|
+
const { timeoutSecs, maxScrollHeight, waitForSecs, scrollDownAndUp, buttonSelector, stopScrollCallback } = parseArgument(options, infiniteScrollOptionsSchema);
|
|
274
287
|
let finished;
|
|
275
288
|
const startTime = Date.now();
|
|
276
289
|
const CHECK_INTERVAL_MILLIS = 1000;
|
|
@@ -347,19 +360,11 @@ export async function infiniteScroll(page, options = {}) {
|
|
|
347
360
|
* @param [options]
|
|
348
361
|
*/
|
|
349
362
|
export async function saveSnapshot(page, options = {}) {
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
key: ow.optional.string.nonEmpty,
|
|
353
|
-
screenshotQuality: ow.optional.number,
|
|
354
|
-
saveScreenshot: ow.optional.boolean,
|
|
355
|
-
saveHtml: ow.optional.boolean,
|
|
356
|
-
keyValueStoreName: ow.optional.string,
|
|
357
|
-
config: ow.optional.object,
|
|
358
|
-
}));
|
|
359
|
-
const { key = 'SNAPSHOT', screenshotQuality = 50, saveScreenshot = true, saveHtml = true, keyValueStoreName, config, } = options;
|
|
363
|
+
parseArgument(page, validators.browserPage);
|
|
364
|
+
const { key, screenshotQuality, saveScreenshot, saveHtml, keyValueStoreName, configuration } = parseArgument(options, saveSnapshotOptionsSchema);
|
|
360
365
|
try {
|
|
361
|
-
const store = await KeyValueStore.open(keyValueStoreName, {
|
|
362
|
-
|
|
366
|
+
const store = await KeyValueStore.open(keyValueStoreName ? { name: keyValueStoreName } : null, {
|
|
367
|
+
configuration: configuration ?? Configuration.getGlobalConfiguration(),
|
|
363
368
|
});
|
|
364
369
|
if (saveScreenshot) {
|
|
365
370
|
const screenshotName = `${key}.jpg`;
|
|
@@ -394,28 +399,28 @@ export async function saveSnapshot(page, options = {}) {
|
|
|
394
399
|
* @param ignoreShadowRoots
|
|
395
400
|
*/
|
|
396
401
|
export async function parseWithCheerio(page, ignoreShadowRoots = false, ignoreIframes = false) {
|
|
397
|
-
|
|
402
|
+
parseArgument(page, validators.browserPage);
|
|
403
|
+
const snapshot = await page.evaluateHandle(`(${snapshotPageWithIframes.toString()})(document, ${ignoreShadowRoots ? 'null' : expandShadowRoots.toString()})`);
|
|
404
|
+
const pageContent = (await (await snapshot.getProperty('html')).jsonValue());
|
|
405
|
+
// Full cheerio (parse5) import for browser compliant parser
|
|
406
|
+
const { load } = await import('cheerio');
|
|
407
|
+
const $ = load(pageContent);
|
|
398
408
|
if (page.frames().length > 1 && !ignoreIframes) {
|
|
399
|
-
const
|
|
400
|
-
await Promise.all(
|
|
409
|
+
const iframes = await (await snapshot.getProperty('iframes')).getProperties();
|
|
410
|
+
await Promise.all([...iframes].map(async ([id, handle]) => {
|
|
401
411
|
try {
|
|
402
|
-
const iframe = await
|
|
412
|
+
const iframe = await handle.asElement()?.contentFrame();
|
|
403
413
|
if (iframe) {
|
|
404
414
|
const getIframeHTML = async () => {
|
|
405
415
|
try {
|
|
406
|
-
return iframe.locator('body').first().innerHTML();
|
|
416
|
+
return await iframe.locator('body').first().innerHTML();
|
|
407
417
|
}
|
|
408
418
|
catch {
|
|
409
419
|
return iframe.content();
|
|
410
420
|
}
|
|
411
421
|
};
|
|
412
422
|
const contents = await getIframeHTML();
|
|
413
|
-
|
|
414
|
-
const replacementNode = document.createElement('div');
|
|
415
|
-
replacementNode.innerHTML = c;
|
|
416
|
-
replacementNode.className = 'crawlee-iframe-replacement';
|
|
417
|
-
f.replaceWith(replacementNode);
|
|
418
|
-
}, contents);
|
|
423
|
+
$(`iframe[data-crawlee-iframe-id="${id}"]`).replaceWith(`<div class="crawlee-iframe-replacement">${contents}</div>`);
|
|
419
424
|
}
|
|
420
425
|
}
|
|
421
426
|
catch (error) {
|
|
@@ -423,40 +428,9 @@ export async function parseWithCheerio(page, ignoreShadowRoots = false, ignoreIf
|
|
|
423
428
|
}
|
|
424
429
|
}));
|
|
425
430
|
}
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
const pageContent = html || (await page.content());
|
|
430
|
-
return cheerio.load(pageContent);
|
|
431
|
-
}
|
|
432
|
-
let idcacPlaywright = null;
|
|
433
|
-
async function getIdcacPlaywright() {
|
|
434
|
-
if (idcacPlaywright)
|
|
435
|
-
return idcacPlaywright;
|
|
436
|
-
try {
|
|
437
|
-
idcacPlaywright = await import('idcac-playwright');
|
|
438
|
-
}
|
|
439
|
-
catch (error) {
|
|
440
|
-
getLog().warning(`Failed to import 'idcac-playwright'.
|
|
441
|
-
|
|
442
|
-
We recently made idcac-playwright an optional dependency due to licensing issues.
|
|
443
|
-
To use this feature, please install it manually by running
|
|
444
|
-
|
|
445
|
-
npm install idcac-playwright
|
|
446
|
-
|
|
447
|
-
Original error message follows:
|
|
448
|
-
|
|
449
|
-
${error.message}
|
|
450
|
-
`);
|
|
451
|
-
}
|
|
452
|
-
return idcacPlaywright;
|
|
453
|
-
}
|
|
454
|
-
export async function closeCookieModals(page) {
|
|
455
|
-
ow(page, ow.object.validate(validators.browserPage));
|
|
456
|
-
const idcac = await getIdcacPlaywright();
|
|
457
|
-
if (idcac?.getInjectableScript()) {
|
|
458
|
-
await page.evaluate(idcac.getInjectableScript());
|
|
459
|
-
}
|
|
431
|
+
await snapshot.dispose();
|
|
432
|
+
$('[data-crawlee-iframe-id]').removeAttr('data-crawlee-iframe-id');
|
|
433
|
+
return $;
|
|
460
434
|
}
|
|
461
435
|
/**
|
|
462
436
|
* This helper tries to solve the Cloudflare challenge automatically by clicking on the checkbox.
|
|
@@ -465,65 +439,92 @@ export async function closeCookieModals(page) {
|
|
|
465
439
|
* result in a SessionError which will be automatically retried, so only successful requests will get
|
|
466
440
|
* into the `requestHandler`.
|
|
467
441
|
*
|
|
442
|
+
* On a successfully solved challenge the page is reloaded and the new {@link Response} is returned, so
|
|
443
|
+
* it can be propagated back to the crawling context via a hook return value (see
|
|
444
|
+
* {@link handleCloudflareChallengeHook}). Thanks to that, the 403 status of the challenge page does not
|
|
445
|
+
* need to be removed from `blockedStatusCodes` - a solved challenge replaces the response before the
|
|
446
|
+
* blocked-status check runs, and an unsolved one is retried with a fresh session.
|
|
447
|
+
*
|
|
468
448
|
* Works best with camoufox.
|
|
469
449
|
*
|
|
470
450
|
* **Example usage**
|
|
471
451
|
* ```ts
|
|
472
452
|
* postNavigationHooks: [
|
|
473
|
-
* async (
|
|
474
|
-
* await handleCloudflareChallenge();
|
|
453
|
+
* async (context) => {
|
|
454
|
+
* const response = await context.handleCloudflareChallenge();
|
|
455
|
+
* // `{ response: undefined }` would replace the navigation response and skip the blocked-status check
|
|
456
|
+
* return response && { response };
|
|
475
457
|
* },
|
|
476
458
|
* ],
|
|
477
459
|
* ```
|
|
478
460
|
*
|
|
479
461
|
* @param page Playwright [`Page`](https://playwright.dev/docs/api/class-page) object
|
|
480
462
|
* @param url current URL for request identification, only used for logging
|
|
481
|
-
* @param [session] current session object
|
|
482
463
|
* @param [options]
|
|
464
|
+
* @param [response] navigation response, used to poll for late-rendered challenge markup when it signals a likely challenge
|
|
483
465
|
*/
|
|
484
|
-
async function handleCloudflareChallenge(page, url,
|
|
485
|
-
//
|
|
486
|
-
|
|
487
|
-
//
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
return document.querySelector('h1')?.textContent?.trim().includes('Sorry, you have been blocked');
|
|
466
|
+
export async function handleCloudflareChallenge(page, url, options = {}, response) {
|
|
467
|
+
// The options object may outlive this call (the pre-wrapped hook reuses one instance for all
|
|
468
|
+
// requests and retries), so the defaults are kept local instead of being memoized on `options` -
|
|
469
|
+
// memoizing them would pin the closed-over `page` of the first call forever.
|
|
470
|
+
const isBlockedCallback = options.isBlockedCallback ??
|
|
471
|
+
(async (p) => {
|
|
472
|
+
const isBlocked = await p.evaluate(() => {
|
|
473
|
+
return document.querySelector('h1')?.textContent?.trim().includes('Sorry, you have been blocked');
|
|
474
|
+
});
|
|
475
|
+
return !!isBlocked;
|
|
495
476
|
});
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
477
|
+
const isChallengeCallback = options.isChallengeCallback ??
|
|
478
|
+
(async (p) => {
|
|
479
|
+
return await p.evaluate(async () => {
|
|
480
|
+
// Cloudflare keeps reshuffling the wrapper elements between `.footer-inner` and `.ray-id`,
|
|
481
|
+
// so only the stable outer classes are matched.
|
|
482
|
+
return !!document.querySelector('.footer .footer-inner .ray-id');
|
|
483
|
+
});
|
|
501
484
|
});
|
|
502
|
-
};
|
|
503
485
|
const retryBlocked = async () => {
|
|
504
|
-
const isBlocked = await
|
|
486
|
+
const isBlocked = await isBlockedCallback(page).catch(() => false);
|
|
505
487
|
if (isBlocked) {
|
|
506
488
|
throw new SessionError(`Blocked by Cloudflare when processing ${url}`);
|
|
507
489
|
}
|
|
508
490
|
};
|
|
509
491
|
// check if we ended up on the CF challenge page
|
|
510
492
|
const isChallenge = async () => {
|
|
511
|
-
return
|
|
493
|
+
return isChallengeCallback(page).catch(async () => {
|
|
494
|
+
// the challenge page navigates itself, which destroys the context of an in-flight check
|
|
495
|
+
await page.waitForLoadState('domcontentloaded').catch(() => { });
|
|
496
|
+
return isChallengeCallback(page).catch(() => false);
|
|
497
|
+
});
|
|
512
498
|
};
|
|
513
|
-
|
|
499
|
+
// The challenge markup can finish rendering only after the `load` event, so when the response signals
|
|
500
|
+
// a likely challenge, poll for it instead of checking once. A 403 alone is not enough - it must come
|
|
501
|
+
// from Cloudflare (the `cf-ray` header), so 403s served by other stacks keep failing fast.
|
|
502
|
+
const headers = response?.headers() ?? {};
|
|
503
|
+
const likelyChallenge = headers['cf-mitigated'] === 'challenge' || (response?.status() === 403 && 'cf-ray' in headers);
|
|
504
|
+
let detected = await isChallenge();
|
|
505
|
+
for (let i = 0; !detected && likelyChallenge && i < 10; i++) {
|
|
506
|
+
// a hard-blocked page never turns into a challenge, so fail fast instead of finishing the poll
|
|
507
|
+
await retryBlocked();
|
|
508
|
+
await sleep(500);
|
|
509
|
+
detected = await isChallenge();
|
|
510
|
+
}
|
|
511
|
+
if (!detected) {
|
|
514
512
|
await retryBlocked();
|
|
515
|
-
return;
|
|
513
|
+
return undefined;
|
|
516
514
|
}
|
|
517
515
|
const logLevel = options.verbose ? 'info' : 'debug';
|
|
518
516
|
getLog()[logLevel](`Detected Cloudflare challenge at ${url}, trying to solve it. This can take up to ${10 + (options.sleepSecs ?? 10)} seconds.`);
|
|
519
517
|
const bb = await page
|
|
520
518
|
.evaluate(() => {
|
|
521
|
-
|
|
519
|
+
// Prefer the actual challenge widget (the box holding the Turnstile checkbox input);
|
|
520
|
+
// fall back to the first content div for older challenge layouts.
|
|
521
|
+
const div = document.querySelector('.main-content div:has(input[id^="cf-chl-widget-"])') ??
|
|
522
|
+
document.querySelector('.main-content div');
|
|
522
523
|
return div?.getBoundingClientRect();
|
|
523
524
|
})
|
|
524
525
|
.catch(() => undefined);
|
|
525
526
|
if (!bb) {
|
|
526
|
-
return;
|
|
527
|
+
return undefined;
|
|
527
528
|
}
|
|
528
529
|
const randomOffset = (range) => {
|
|
529
530
|
return Math.round(100 * range * Math.random()) / 100;
|
|
@@ -551,7 +552,10 @@ async function handleCloudflareChallenge(page, url, session, options = {}) {
|
|
|
551
552
|
// we can click on the text too, so X can be a bit larger
|
|
552
553
|
const xRandomized = x + randomOffset(10);
|
|
553
554
|
const yRandomized = y + randomOffset(10);
|
|
554
|
-
getLog()[logLevel](`Trying to click on the Cloudflare checkbox at ${url}`, {
|
|
555
|
+
getLog()[logLevel](`Trying to click on the Cloudflare checkbox at ${url}`, {
|
|
556
|
+
x: xRandomized,
|
|
557
|
+
y: yRandomized,
|
|
558
|
+
});
|
|
555
559
|
await page.mouse.click(xRandomized, yRandomized);
|
|
556
560
|
// sometimes the checkbox is lower (could be caused by a lag when rendering the logo)
|
|
557
561
|
await page.mouse.click(xRandomized, yRandomized + 35);
|
|
@@ -561,21 +565,8 @@ async function handleCloudflareChallenge(page, url, session, options = {}) {
|
|
|
561
565
|
throw new SessionError(`Blocked by Cloudflare when processing ${url}`);
|
|
562
566
|
}
|
|
563
567
|
await retryBlocked();
|
|
568
|
+
// Reload to obtain a fresh Response without the challenge interstitial, which the caller can
|
|
569
|
+
// propagate back into the crawling context so downstream status-code checks see the new value.
|
|
570
|
+
return (await page.reload()) ?? undefined;
|
|
564
571
|
}
|
|
565
572
|
export { enqueueLinksByClickingElements };
|
|
566
|
-
/** @internal */
|
|
567
|
-
export const playwrightUtils = {
|
|
568
|
-
injectFile,
|
|
569
|
-
injectJQuery,
|
|
570
|
-
gotoExtended,
|
|
571
|
-
blockRequests,
|
|
572
|
-
enqueueLinksByClickingElements,
|
|
573
|
-
parseWithCheerio,
|
|
574
|
-
infiniteScroll,
|
|
575
|
-
saveSnapshot,
|
|
576
|
-
compileScript,
|
|
577
|
-
closeCookieModals,
|
|
578
|
-
RenderingTypePredictor,
|
|
579
|
-
handleCloudflareChallenge,
|
|
580
|
-
};
|
|
581
|
-
//# sourceMappingURL=playwright-utils.js.map
|