@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.
@@ -20,12 +20,12 @@
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, parseArgument, schemas, serviceLocator, SessionError, validators, } from '@crawlee/browser';
24
- import { expandShadowRoots, sleep } from '@crawlee/utils';
23
+ import { Configuration, KeyValueStore, serviceLocator, SessionError, validators } from '@crawlee/browser';
24
+ import { sleep } from '@crawlee/utils';
25
+ import { expandShadowRoots, parseArgument, schemas } from '@crawlee/utils/internal';
25
26
  import { z } from 'zod';
26
27
  import { LruCache } from '@apify/datastructures';
27
28
  import { enqueueLinksByClickingElements } from '../enqueue-links/click-elements.js';
28
- import { RenderingTypePredictor } from './rendering-type-prediction.js';
29
29
  const getLog = () => serviceLocator.getChildLog('Playwright Utils');
30
30
  const require = createRequire(import.meta.url);
31
31
  const jqueryPath = require.resolve('jquery');
@@ -404,6 +404,7 @@ export async function parseWithCheerio(page, ignoreShadowRoots = false, ignoreIf
404
404
  ? null
405
405
  : (await page.evaluate(`(${expandShadowRoots.toString()})(document)`));
406
406
  const pageContent = html || (await page.content());
407
+ // Full cheerio (parse5) import for browser compliant parser
407
408
  const { load } = await import('cheerio');
408
409
  const $ = load(pageContent);
409
410
  if (page.frames().length > 1 && !ignoreIframes) {
@@ -437,35 +438,6 @@ export async function parseWithCheerio(page, ignoreShadowRoots = false, ignoreIf
437
438
  }
438
439
  return $;
439
440
  }
440
- let idcacPlaywright = null;
441
- async function getIdcacPlaywright() {
442
- if (idcacPlaywright)
443
- return idcacPlaywright;
444
- try {
445
- idcacPlaywright = await import('idcac-playwright');
446
- }
447
- catch (error) {
448
- getLog().warning(`Failed to import 'idcac-playwright'.
449
-
450
- We recently made idcac-playwright an optional dependency due to licensing issues.
451
- To use this feature, please install it manually by running
452
-
453
- npm install idcac-playwright
454
-
455
- Original error message follows:
456
-
457
- ${error.message}
458
- `);
459
- }
460
- return idcacPlaywright;
461
- }
462
- export async function closeCookieModals(page) {
463
- parseArgument(page, validators.browserPage);
464
- const idcac = await getIdcacPlaywright();
465
- if (idcac?.getInjectableScript()) {
466
- await page.evaluate(idcac.getInjectableScript());
467
- }
468
- }
469
441
  /**
470
442
  * This helper tries to solve the Cloudflare challenge automatically by clicking on the checkbox.
471
443
  * It will try to detect the Cloudflare page, click on the checkbox, and wait for 10 seconds (configurable
@@ -490,7 +462,7 @@ export async function closeCookieModals(page) {
490
462
  * @param url current URL for request identification, only used for logging
491
463
  * @param [options]
492
464
  */
493
- async function handleCloudflareChallenge(page, url, options = {}) {
465
+ export async function handleCloudflareChallenge(page, url, options = {}) {
494
466
  options.isBlockedCallback ??= async () => {
495
467
  const isBlocked = await page.evaluate(() => {
496
468
  return document.querySelector('h1')?.textContent?.trim().includes('Sorry, you have been blocked');
@@ -512,7 +484,11 @@ async function handleCloudflareChallenge(page, url, options = {}) {
512
484
  };
513
485
  // check if we ended up on the CF challenge page
514
486
  const isChallenge = async () => {
515
- return options.isChallengeCallback(page).catch(() => false);
487
+ return options.isChallengeCallback(page).catch(async () => {
488
+ // the challenge page navigates itself, which destroys the context of an in-flight check
489
+ await page.waitForLoadState('domcontentloaded').catch(() => { });
490
+ return options.isChallengeCallback(page).catch(() => false);
491
+ });
516
492
  };
517
493
  if (!(await isChallenge())) {
518
494
  await retryBlocked();
@@ -576,18 +552,3 @@ async function handleCloudflareChallenge(page, url, options = {}) {
576
552
  return (await page.reload()) ?? undefined;
577
553
  }
578
554
  export { enqueueLinksByClickingElements };
579
- /** @internal */
580
- export const playwrightUtils = {
581
- injectFile,
582
- injectJQuery,
583
- gotoExtended,
584
- blockRequests,
585
- enqueueLinksByClickingElements,
586
- parseWithCheerio,
587
- infiniteScroll,
588
- saveSnapshot,
589
- compileScript,
590
- closeCookieModals,
591
- RenderingTypePredictor,
592
- handleCloudflareChallenge,
593
- };
@@ -1,4 +1,5 @@
1
1
  import type { RecoverableStatePersistenceOptions, Request } from '@crawlee/core';
2
+ import type { Awaitable } from '@crawlee/types';
2
3
  export type RenderingType = 'clientOnly' | 'static';
3
4
  export interface RenderingTypePredictorOptions {
4
5
  /** A number between 0 and 1 that determines the desired ratio of rendering type detections */
@@ -8,31 +9,43 @@ export interface RenderingTypePredictorOptions {
8
9
  /**
9
10
  * Minimal contract that any object passed to {@link AdaptivePlaywrightCrawler} as its
10
11
  * `renderingTypePredictor` option must satisfy.
11
- *
12
- * @experimental
13
12
  */
14
13
  export interface IRenderingTypePredictor {
15
- /** Predict the rendering type for a request, and how likely the crawler should be to verify it. */
16
- predict(request: Request): {
14
+ /**
15
+ * Predict the rendering type for a request, and how likely the crawler should be to verify it.
16
+ *
17
+ * Called once per request, before navigation - the crawler awaits it, so prefer loading whatever the
18
+ * prediction needs up front over per-request I/O.
19
+ */
20
+ predict(request: Request): Awaitable<{
17
21
  renderingType: RenderingType;
18
22
  detectionProbabilityRecommendation: number;
19
- };
20
- /** Report a detected rendering type, so that future predictions can take it into account. */
21
- storeResult(requests: Request | Request[], renderingType: RenderingType): void;
23
+ }>;
24
+ /**
25
+ * Report a rendering type established by a detection, or `clientOnly` when the `resultChecker` rejected an
26
+ * HTTP-only result, so that future predictions can take it into account.
27
+ *
28
+ * The crawler does not await this per detection - it collects the returned promises and drains them in
29
+ * `teardown()`, so an implementation that persists results asynchronously can keep batching its writes
30
+ * and still be sure they land before the crawl ends.
31
+ */
32
+ storeResult(requests: Request | Request[], renderingType: RenderingType): Awaitable<void>;
22
33
  }
23
34
  /**
24
35
  * Stores rendering type information for previously crawled URLs and predicts the rendering type for URLs that have yet to be crawled and recommends when rendering type detection should be performed.
25
- *
26
- * @experimental
27
36
  */
28
37
  export declare class RenderingTypePredictor implements IRenderingTypePredictor {
29
38
  #private;
30
- private state;
31
39
  constructor({ detectionRatio, persistenceOptions }: RenderingTypePredictorOptions);
32
40
  /**
33
41
  * Initialize the predictor by restoring persisted state.
34
42
  */
35
43
  initialize(): Promise<void>;
44
+ /**
45
+ * Stop persisting the model, writing it out one last time. `initialize()` reopens the persistence window.
46
+ */
47
+ teardown(): Promise<void>;
48
+ [Symbol.asyncDispose](): Promise<void>;
36
49
  /**
37
50
  * Predict the rendering type for a given URL and request label.
38
51
  */
@@ -44,7 +57,4 @@ export declare class RenderingTypePredictor implements IRenderingTypePredictor {
44
57
  * Store the rendering type for a given URL and request label. This updates the underlying prediction model, which may be costly.
45
58
  */
46
59
  storeResult(requests: Request | Request[], renderingType: RenderingType): void;
47
- private resultCount;
48
- private calculateFeatureVector;
49
- private retrain;
50
60
  }
@@ -62,16 +62,13 @@ const stateCodec = z.codec(persistedState, predictorState, {
62
62
  });
63
63
  /**
64
64
  * Stores rendering type information for previously crawled URLs and predicts the rendering type for URLs that have yet to be crawled and recommends when rendering type detection should be performed.
65
- *
66
- * @experimental
67
65
  */
68
66
  export class RenderingTypePredictor {
69
67
  #detectionRatio;
70
- // kept as TS-private: tests reach for it at runtime
71
- state;
68
+ #state;
72
69
  constructor({ detectionRatio, persistenceOptions }) {
73
70
  this.#detectionRatio = detectionRatio;
74
- this.state = new RecoverableState({
71
+ this.#state = new RecoverableState({
75
72
  defaultState: () => stateCodec.decode({}),
76
73
  // The codec validates in the decode direction, so it is a Standard Schema as-is; encoding needs a call.
77
74
  deserialize: stateCodec,
@@ -85,32 +82,41 @@ export class RenderingTypePredictor {
85
82
  * Initialize the predictor by restoring persisted state.
86
83
  */
87
84
  async initialize() {
88
- await this.state.initialize();
85
+ await this.#state.initialize();
86
+ }
87
+ /**
88
+ * Stop persisting the model, writing it out one last time. `initialize()` reopens the persistence window.
89
+ */
90
+ async teardown() {
91
+ await this.#state.teardown();
92
+ }
93
+ async [Symbol.asyncDispose]() {
94
+ await this.teardown();
89
95
  }
90
96
  /**
91
97
  * Predict the rendering type for a given URL and request label.
92
98
  */
93
99
  predict({ url, loadedUrl, label }) {
94
- const { logreg } = this.state.currentValue;
100
+ const { logreg } = this.#state.currentValue;
95
101
  if (logreg.classifiers.length === 0) {
96
102
  return { renderingType: 'clientOnly', detectionProbabilityRecommendation: 1 };
97
103
  }
98
104
  const predictionUrl = new URL(loadedUrl ?? url);
99
- const urlFeature = new Matrix([this.calculateFeatureVector(urlComponents(predictionUrl), label)]);
105
+ const urlFeature = new Matrix([this.#calculateFeatureVector(urlComponents(predictionUrl), label)]);
100
106
  const [prediction] = logreg.predict(urlFeature);
101
107
  const scores = [logreg.classifiers[0].testScores(urlFeature), logreg.classifiers[1].testScores(urlFeature)];
102
108
  return {
103
109
  renderingType: prediction === 1 ? 'static' : 'clientOnly',
104
110
  detectionProbabilityRecommendation: Math.abs(scores[0] - scores[1]) < 0.1
105
111
  ? 1
106
- : this.#detectionRatio * Math.max(1, 5 - this.resultCount(label)),
112
+ : this.#detectionRatio * Math.max(1, 5 - this.#resultCount(label)),
107
113
  };
108
114
  }
109
115
  /**
110
116
  * Store the rendering type for a given URL and request label. This updates the underlying prediction model, which may be costly.
111
117
  */
112
118
  storeResult(requests, renderingType) {
113
- const state = this.state.currentValue;
119
+ const state = this.#state.currentValue;
114
120
  for (const { url, loadedUrl, label } of Array.isArray(requests) ? requests : [requests]) {
115
121
  const resultUrl = new URL(loadedUrl ?? url);
116
122
  if (!state.detectionResults.has(renderingType)) {
@@ -121,33 +127,33 @@ export class RenderingTypePredictor {
121
127
  }
122
128
  state.detectionResults.get(renderingType).get(label).push(urlComponents(resultUrl));
123
129
  }
124
- this.retrain();
130
+ this.#retrain();
125
131
  }
126
- resultCount(label) {
127
- return Array.from(this.state.currentValue.detectionResults.values())
132
+ #resultCount(label) {
133
+ return Array.from(this.#state.currentValue.detectionResults.values())
128
134
  .map((results) => results.get(label)?.length ?? 0)
129
135
  .reduce((acc, value) => acc + value, 0);
130
136
  }
131
- calculateFeatureVector(url, label) {
137
+ #calculateFeatureVector(url, label) {
132
138
  return [
133
- mean((this.state.currentValue.detectionResults.get('static')?.get(label) ?? []).map((otherUrl) => calculateUrlSimilarity(url, otherUrl) ?? 0)) ?? 0,
134
- mean((this.state.currentValue.detectionResults.get('clientOnly')?.get(label) ?? []).map((otherUrl) => calculateUrlSimilarity(url, otherUrl) ?? 0)) ?? 0,
139
+ mean((this.#state.currentValue.detectionResults.get('static')?.get(label) ?? []).map((otherUrl) => calculateUrlSimilarity(url, otherUrl) ?? 0)) ?? 0,
140
+ mean((this.#state.currentValue.detectionResults.get('clientOnly')?.get(label) ?? []).map((otherUrl) => calculateUrlSimilarity(url, otherUrl) ?? 0)) ?? 0,
135
141
  ];
136
142
  }
137
- retrain() {
143
+ #retrain() {
138
144
  const X = [
139
145
  [0, 1],
140
146
  [1, 0],
141
147
  ];
142
148
  const Y = [0, 1];
143
- for (const [renderingType, urlsByLabel] of this.state.currentValue.detectionResults.entries()) {
149
+ for (const [renderingType, urlsByLabel] of this.#state.currentValue.detectionResults.entries()) {
144
150
  for (const [label, urls] of urlsByLabel) {
145
151
  for (const url of urls) {
146
- X.push(this.calculateFeatureVector(url, label));
152
+ X.push(this.#calculateFeatureVector(url, label));
147
153
  Y.push(renderingType === 'static' ? 1 : 0);
148
154
  }
149
155
  }
150
156
  }
151
- this.state.currentValue.logreg.train(new Matrix(X), Matrix.columnVector(Y));
157
+ this.#state.currentValue.logreg.train(new Matrix(X), Matrix.columnVector(Y));
152
158
  }
153
159
  }
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@crawlee/playwright",
3
- "version": "4.0.0-rc.0",
3
+ "version": "4.0.0-rc.2",
4
4
  "description": "The scalable web crawling and scraping library for JavaScript/Node.js. Enables development of data extraction and web automation jobs (not only) with headless Chrome and Puppeteer.",
5
5
  "engines": {
6
- "node": ">=22.0.0"
6
+ "node": ">=22.13.0"
7
7
  },
8
8
  "type": "module",
9
9
  "exports": {
@@ -47,32 +47,29 @@
47
47
  "access": "public"
48
48
  },
49
49
  "dependencies": {
50
- "@apify/datastructures": "^2.0.3",
51
- "@apify/timeout": "^0.4.4",
52
- "@crawlee/basic": "4.0.0-rc.0",
53
- "@crawlee/browser": "4.0.0-rc.0",
54
- "@crawlee/browser-pool": "4.0.0-rc.0",
55
- "@crawlee/cheerio": "4.0.0-rc.0",
56
- "@crawlee/core": "4.0.0-rc.0",
57
- "@crawlee/types": "4.0.0-rc.0",
58
- "@crawlee/utils": "4.0.0-rc.0",
59
- "cheerio": "^1.0.0",
50
+ "@apify/datastructures": "^3.0.1",
51
+ "@apify/timeout": "^1.0.1",
52
+ "@crawlee/basic": "4.0.0-rc.2",
53
+ "@crawlee/browser": "4.0.0-rc.2",
54
+ "@crawlee/browser-pool": "4.0.0-rc.2",
55
+ "@crawlee/cheerio": "4.0.0-rc.2",
56
+ "@crawlee/core": "4.0.0-rc.2",
57
+ "@crawlee/http-client": "4.0.0-rc.2",
58
+ "@crawlee/types": "4.0.0-rc.2",
59
+ "@crawlee/utils": "4.0.0-rc.2",
60
+ "cheerio": "^1.2.0",
61
+ "domhandler": "^6.0.1",
60
62
  "jquery": "^3.7.1",
61
63
  "ml-logistic-regression": "^2.0.0",
62
- "ml-matrix": "^6.12.1",
64
+ "ml-matrix": "^6.15.1",
63
65
  "string-comparison": "^1.3.0",
64
- "tslib": "^2.8.1",
65
- "type-fest": "^4.0.0",
66
- "zod": "^4.4.3"
66
+ "tslib": "^2.9.1",
67
+ "zod": "^4.6.7"
67
68
  },
68
69
  "peerDependencies": {
69
- "idcac-playwright": "^0.2.0",
70
70
  "playwright": "*"
71
71
  },
72
72
  "peerDependenciesMeta": {
73
- "idcac-playwright": {
74
- "optional": true
75
- },
76
73
  "playwright": {
77
74
  "optional": true
78
75
  }
@@ -84,5 +81,5 @@
84
81
  }
85
82
  }
86
83
  },
87
- "gitHead": "79ab33dacdacb83e0197e6516d145f3aceef80c7"
84
+ "gitHead": "a9b623229cd7d1bff5063fc82940efebaea47165"
88
85
  }