@crawlee/playwright 4.0.0-beta.8 → 4.0.0-beta.81
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 +17 -13
- package/index.d.ts +0 -1
- package/index.js +0 -1
- package/internals/adaptive-playwright-crawler.d.ts +114 -60
- package/internals/adaptive-playwright-crawler.js +349 -210
- package/internals/enqueue-links/click-elements.d.ts +32 -14
- package/internals/enqueue-links/click-elements.js +57 -25
- package/internals/playwright-crawler.d.ts +96 -77
- package/internals/playwright-crawler.js +79 -38
- package/internals/playwright-launcher.d.ts +2 -1
- package/internals/playwright-launcher.js +1 -2
- package/internals/utils/playwright-utils.d.ts +54 -17
- package/internals/utils/playwright-utils.js +96 -83
- package/internals/utils/rendering-type-prediction.d.ts +11 -11
- package/internals/utils/rendering-type-prediction.js +67 -26
- package/package.json +16 -11
- 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
- package/tsconfig.build.tsbuildinfo +0 -1
|
@@ -1,8 +1,9 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
2
|
+
import { BasicCrawler } from '@crawlee/basic';
|
|
1
3
|
import { extractUrlsFromPage } from '@crawlee/browser';
|
|
2
|
-
import {
|
|
4
|
+
import { CheerioCrawler } from '@crawlee/cheerio';
|
|
5
|
+
import { RequestHandlerError, RequestHandlerResult, resolveBaseUrlForEnqueueLinksFiltering, Router, serviceLocator, Statistics, withCheckedStorageAccess, } from '@crawlee/core';
|
|
3
6
|
import { extractUrlsFromCheerio } from '@crawlee/utils';
|
|
4
|
-
import { load } from 'cheerio';
|
|
5
|
-
import isEqual from 'lodash.isequal';
|
|
6
7
|
import { addTimeoutToPromise } from '@apify/timeout';
|
|
7
8
|
import { PlaywrightCrawler } from './playwright-crawler.js';
|
|
8
9
|
import { RenderingTypePredictor } from './utils/rendering-type-prediction.js';
|
|
@@ -18,8 +19,8 @@ class AdaptivePlaywrightCrawlerStatistics extends Statistics {
|
|
|
18
19
|
this.state.browserRequestHandlerRuns = 0;
|
|
19
20
|
this.state.renderingTypeMispredictions = 0;
|
|
20
21
|
}
|
|
21
|
-
async
|
|
22
|
-
await super.
|
|
22
|
+
async maybeLoadStatistics() {
|
|
23
|
+
await super.maybeLoadStatistics();
|
|
23
24
|
const savedState = await this.keyValueStore?.getValue(this.persistStateKey);
|
|
24
25
|
if (!savedState) {
|
|
25
26
|
return;
|
|
@@ -80,27 +81,32 @@ const proxyLogMethods = [
|
|
|
80
81
|
*
|
|
81
82
|
* @experimental
|
|
82
83
|
*/
|
|
83
|
-
export class AdaptivePlaywrightCrawler extends
|
|
84
|
-
config;
|
|
85
|
-
adaptiveRequestHandler;
|
|
84
|
+
export class AdaptivePlaywrightCrawler extends BasicCrawler {
|
|
86
85
|
renderingTypePredictor;
|
|
87
86
|
resultChecker;
|
|
87
|
+
shouldPropagateError;
|
|
88
88
|
resultComparator;
|
|
89
89
|
preventDirectStorageAccess;
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
constructor(options = {}
|
|
97
|
-
const { requestHandler, renderingTypeDetectionRatio = 0.1, renderingTypePredictor, resultChecker, resultComparator, statisticsOptions, preventDirectStorageAccess = true, ...rest } = options;
|
|
98
|
-
super(
|
|
99
|
-
|
|
100
|
-
|
|
90
|
+
staticContextPipeline;
|
|
91
|
+
browserContextPipeline;
|
|
92
|
+
individualRequestHandlerTimeoutMillis;
|
|
93
|
+
resultObjects = new WeakMap();
|
|
94
|
+
inFlightRenderingTypeDetections = 0;
|
|
95
|
+
teardownHooks = [];
|
|
96
|
+
constructor(options = {}) {
|
|
97
|
+
const { requestHandler, renderingTypeDetectionRatio = 0.1, renderingTypePredictor, resultChecker, shouldPropagateError, resultComparator, statisticsOptions, preventDirectStorageAccess = true, requestHandlerTimeoutSecs = 60, errorHandler, failedRequestHandler, preNavigationHooks = [], postNavigationHooks = [], extendContext, contextPipelineBuilder, ...rest } = options;
|
|
98
|
+
super({
|
|
99
|
+
...rest,
|
|
100
|
+
errorHandler,
|
|
101
|
+
failedRequestHandler,
|
|
102
|
+
requestHandler,
|
|
103
|
+
contextPipelineBuilder: contextPipelineBuilder ?? (() => this.buildContextPipeline()),
|
|
104
|
+
});
|
|
105
|
+
this.individualRequestHandlerTimeoutMillis = requestHandlerTimeoutSecs * 1000;
|
|
101
106
|
this.renderingTypePredictor =
|
|
102
107
|
renderingTypePredictor ?? new RenderingTypePredictor({ detectionRatio: renderingTypeDetectionRatio });
|
|
103
108
|
this.resultChecker = resultChecker ?? (() => true);
|
|
109
|
+
this.shouldPropagateError = shouldPropagateError ?? (() => false);
|
|
104
110
|
if (resultComparator !== undefined) {
|
|
105
111
|
this.resultComparator = resultComparator;
|
|
106
112
|
}
|
|
@@ -112,75 +118,288 @@ export class AdaptivePlaywrightCrawler extends PlaywrightCrawler {
|
|
|
112
118
|
return (resultA.datasetItems.length === resultB.datasetItems.length &&
|
|
113
119
|
resultA.datasetItems.every((itemA, i) => {
|
|
114
120
|
const itemB = resultB.datasetItems[i];
|
|
115
|
-
return
|
|
121
|
+
return isDeepStrictEqual(itemA, itemB);
|
|
116
122
|
}));
|
|
117
123
|
};
|
|
118
124
|
}
|
|
125
|
+
// Each adaptive hook is registered as its own static/browser hook so the underlying
|
|
126
|
+
// `ContextPipeline` handles override merging between hooks for free. The hook signatures
|
|
127
|
+
// are structurally compatible with the underlying crawlers' contexts (subset of fields);
|
|
128
|
+
// the casts just relax the nominal type difference.
|
|
129
|
+
const staticCrawler = new CheerioCrawler({
|
|
130
|
+
...rest,
|
|
131
|
+
statisticsOptions: {
|
|
132
|
+
persistenceOptions: { enable: false },
|
|
133
|
+
},
|
|
134
|
+
preNavigationHooks,
|
|
135
|
+
postNavigationHooks,
|
|
136
|
+
});
|
|
137
|
+
const browserCrawler = new PlaywrightCrawler({
|
|
138
|
+
...rest,
|
|
139
|
+
statisticsOptions: {
|
|
140
|
+
persistenceOptions: { enable: false },
|
|
141
|
+
},
|
|
142
|
+
preNavigationHooks: preNavigationHooks,
|
|
143
|
+
postNavigationHooks: postNavigationHooks,
|
|
144
|
+
});
|
|
145
|
+
this.teardownHooks.push(browserCrawler.teardown.bind(browserCrawler));
|
|
146
|
+
this.staticContextPipeline = staticCrawler.contextPipeline
|
|
147
|
+
.compose({
|
|
148
|
+
action: this.adaptCheerioContext.bind(this),
|
|
149
|
+
})
|
|
150
|
+
.compose({
|
|
151
|
+
action: async (context) => extendContext ? await extendContext(context) : context,
|
|
152
|
+
});
|
|
153
|
+
this.browserContextPipeline = browserCrawler.contextPipeline
|
|
154
|
+
.compose({
|
|
155
|
+
action: this.adaptPlaywrightContext.bind(this),
|
|
156
|
+
})
|
|
157
|
+
.compose({
|
|
158
|
+
action: async (context) => extendContext ? await extendContext(context) : context,
|
|
159
|
+
});
|
|
119
160
|
this.stats = new AdaptivePlaywrightCrawlerStatistics({
|
|
120
161
|
logMessage: `${this.log.getOptions().prefix} request statistics:`,
|
|
121
|
-
config,
|
|
122
162
|
...statisticsOptions,
|
|
123
163
|
});
|
|
124
164
|
this.preventDirectStorageAccess = preventDirectStorageAccess;
|
|
125
165
|
}
|
|
126
|
-
async
|
|
166
|
+
async _init() {
|
|
167
|
+
await this.renderingTypePredictor.initialize();
|
|
168
|
+
return await super._init();
|
|
169
|
+
}
|
|
170
|
+
buildContextPipeline() {
|
|
171
|
+
const errorMessage = (prop) => `The \`${prop}\` property is not available on the outer context pipeline of AdaptivePlaywrightCrawler - it is provided by the inner (static/browser) pipelines`;
|
|
172
|
+
return super.buildContextPipeline().compose({
|
|
173
|
+
action: async ({ request }) => ({
|
|
174
|
+
get request() {
|
|
175
|
+
return request;
|
|
176
|
+
},
|
|
177
|
+
get response() {
|
|
178
|
+
throw new Error(errorMessage('response'));
|
|
179
|
+
},
|
|
180
|
+
get page() {
|
|
181
|
+
throw new Error(errorMessage('page'));
|
|
182
|
+
},
|
|
183
|
+
get querySelector() {
|
|
184
|
+
throw new Error(errorMessage('querySelector'));
|
|
185
|
+
},
|
|
186
|
+
get querySelectorAll() {
|
|
187
|
+
throw new Error(errorMessage('querySelectorAll'));
|
|
188
|
+
},
|
|
189
|
+
get waitForSelector() {
|
|
190
|
+
throw new Error(errorMessage('waitForSelector'));
|
|
191
|
+
},
|
|
192
|
+
get parseWithCheerio() {
|
|
193
|
+
throw new Error(errorMessage('parseWithCheerio'));
|
|
194
|
+
},
|
|
195
|
+
}),
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
async adaptCheerioContext(cheerioContext) {
|
|
199
|
+
// Capture the original response to avoid infinite recursion when the getter is copied to the context
|
|
200
|
+
const result = this.resultObjects.get(cheerioContext);
|
|
201
|
+
if (result === undefined) {
|
|
202
|
+
throw new Error('Logical error - `this.resultObjects` does not contain the result object');
|
|
203
|
+
}
|
|
204
|
+
return {
|
|
205
|
+
get page() {
|
|
206
|
+
throw new Error('Page object was used in HTTP-only request handler');
|
|
207
|
+
},
|
|
208
|
+
async querySelector(selector) {
|
|
209
|
+
return cheerioContext.$(selector).first();
|
|
210
|
+
},
|
|
211
|
+
async querySelectorAll(selector) {
|
|
212
|
+
return cheerioContext.$(selector);
|
|
213
|
+
},
|
|
214
|
+
enqueueLinks: async (options = {}) => {
|
|
215
|
+
const urls = options.urls ??
|
|
216
|
+
extractUrlsFromCheerio(cheerioContext.$, options.selector, options.baseUrl ?? cheerioContext.request.loadedUrl);
|
|
217
|
+
return (await this.enqueueLinks({ ...options, urls }, cheerioContext.request, result));
|
|
218
|
+
},
|
|
219
|
+
response: cheerioContext.response,
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
async adaptPlaywrightContext(playwrightContext) {
|
|
223
|
+
const originalResponse = playwrightContext.response;
|
|
224
|
+
const result = this.resultObjects.get(playwrightContext);
|
|
225
|
+
if (result === undefined) {
|
|
226
|
+
throw new Error('Logical error - `this.resultObjects` does not contain the result object');
|
|
227
|
+
}
|
|
228
|
+
return {
|
|
229
|
+
response: new Response(Uint8Array.from(await originalResponse.body()), {
|
|
230
|
+
headers: originalResponse.headers(),
|
|
231
|
+
status: originalResponse.status(),
|
|
232
|
+
statusText: originalResponse.statusText(),
|
|
233
|
+
}),
|
|
234
|
+
async querySelector(selector, timeoutMs = 5000) {
|
|
235
|
+
const locator = playwrightContext.page.locator(selector).first();
|
|
236
|
+
await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
|
|
237
|
+
const $ = await playwrightContext.parseWithCheerio();
|
|
238
|
+
return $(selector).first();
|
|
239
|
+
},
|
|
240
|
+
async querySelectorAll(selector, timeoutMs = 5000) {
|
|
241
|
+
const locator = playwrightContext.page.locator(selector).first();
|
|
242
|
+
await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
|
|
243
|
+
const $ = await playwrightContext.parseWithCheerio();
|
|
244
|
+
return $(selector);
|
|
245
|
+
},
|
|
246
|
+
enqueueLinks: async (options = {}, timeoutMs = 5000) => {
|
|
247
|
+
// TODO consider using `context.parseWithCheerio` to make this universal and avoid code duplication
|
|
248
|
+
let urls;
|
|
249
|
+
if (options.urls === undefined) {
|
|
250
|
+
const selector = options.selector ?? 'a';
|
|
251
|
+
const locator = playwrightContext.page.locator(selector).first();
|
|
252
|
+
await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
|
|
253
|
+
urls =
|
|
254
|
+
options.urls ??
|
|
255
|
+
(await extractUrlsFromPage(playwrightContext.page, selector, options.baseUrl ?? playwrightContext.request.loadedUrl));
|
|
256
|
+
}
|
|
257
|
+
else {
|
|
258
|
+
urls = options.urls;
|
|
259
|
+
}
|
|
260
|
+
return (await this.enqueueLinks({ ...options, urls }, playwrightContext.request, result));
|
|
261
|
+
},
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
async crawlOne(renderingType, context, useStateFunction) {
|
|
265
|
+
const result = new RequestHandlerResult(serviceLocator.getConfiguration(), AdaptivePlaywrightCrawler.CRAWLEE_STATE_KEY);
|
|
266
|
+
const logs = [];
|
|
267
|
+
const deferredCleanup = [];
|
|
268
|
+
const resultBoundContextHelpers = {
|
|
269
|
+
addRequests: result.addRequests,
|
|
270
|
+
pushData: result.pushData,
|
|
271
|
+
useState: this.allowStorageAccess(useStateFunction),
|
|
272
|
+
getKeyValueStore: this.allowStorageAccess(result.getKeyValueStore),
|
|
273
|
+
log: this.createLogProxy(context.log, logs),
|
|
274
|
+
registerDeferredCleanup: (cleanup) => deferredCleanup.push(cleanup),
|
|
275
|
+
};
|
|
276
|
+
const subCrawlerContext = Object.defineProperties({}, Object.getOwnPropertyDescriptors(context));
|
|
277
|
+
// Mark result-bound helpers as non-configurable so they survive the sub-crawler context pipeline
|
|
278
|
+
// (which would otherwise override them with the sub-crawler's own versions, losing the result binding).
|
|
279
|
+
for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(resultBoundContextHelpers))) {
|
|
280
|
+
Object.defineProperty(subCrawlerContext, key, { ...descriptor, configurable: false });
|
|
281
|
+
}
|
|
282
|
+
this.resultObjects.set(subCrawlerContext, result);
|
|
283
|
+
try {
|
|
284
|
+
const callAdaptiveRequestHandler = async () => {
|
|
285
|
+
if (renderingType === 'static') {
|
|
286
|
+
await this.staticContextPipeline.call(subCrawlerContext, this.requestHandler.bind(this));
|
|
287
|
+
}
|
|
288
|
+
else if (renderingType === 'clientOnly') {
|
|
289
|
+
await this.browserContextPipeline.call(subCrawlerContext, this.requestHandler.bind(this));
|
|
290
|
+
}
|
|
291
|
+
};
|
|
292
|
+
await addTimeoutToPromise(async () => withCheckedStorageAccess(() => {
|
|
293
|
+
if (this.preventDirectStorageAccess) {
|
|
294
|
+
throw new Error('Directly accessing storage in a request handler is not allowed in AdaptivePlaywrightCrawler');
|
|
295
|
+
}
|
|
296
|
+
}, callAdaptiveRequestHandler), this.individualRequestHandlerTimeoutMillis, 'Request handler timed out');
|
|
297
|
+
return { result, ok: true, logs };
|
|
298
|
+
}
|
|
299
|
+
catch (error) {
|
|
300
|
+
return { error, ok: false, logs };
|
|
301
|
+
}
|
|
302
|
+
finally {
|
|
303
|
+
await Promise.all(deferredCleanup.map((cleanup) => cleanup()));
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
async runRequestHandler(crawlingContext) {
|
|
127
307
|
const renderingTypePrediction = this.renderingTypePredictor.predict(crawlingContext.request);
|
|
128
308
|
const shouldDetectRenderingType = Math.random() < renderingTypePrediction.detectionProbabilityRecommendation;
|
|
129
309
|
if (!shouldDetectRenderingType) {
|
|
130
310
|
crawlingContext.log.debug(`Predicted rendering type ${renderingTypePrediction.renderingType} for ${crawlingContext.request.url}`);
|
|
131
311
|
}
|
|
132
|
-
if (renderingTypePrediction.renderingType === 'static' && !shouldDetectRenderingType) {
|
|
133
|
-
crawlingContext.log.debug(`Running HTTP-only request handler for ${crawlingContext.request.url}`);
|
|
134
|
-
this.stats.trackHttpOnlyRequestHandlerRun();
|
|
135
|
-
const plainHTTPRun = await this.runRequestHandlerWithPlainHTTP(crawlingContext);
|
|
136
|
-
if (plainHTTPRun.ok && this.resultChecker(plainHTTPRun.result)) {
|
|
137
|
-
crawlingContext.log.debug(`HTTP-only request handler succeeded for ${crawlingContext.request.url}`);
|
|
138
|
-
plainHTTPRun.logs?.forEach(([log, method, ...args]) => log[method](...args));
|
|
139
|
-
await this.commitResult(crawlingContext, plainHTTPRun.result);
|
|
140
|
-
return;
|
|
141
|
-
}
|
|
142
|
-
if (!plainHTTPRun.ok) {
|
|
143
|
-
crawlingContext.log.exception(plainHTTPRun.error, `HTTP-only request handler failed for ${crawlingContext.request.url}`);
|
|
144
|
-
}
|
|
145
|
-
else {
|
|
146
|
-
crawlingContext.log.warning(`HTTP-only request handler returned a suspicious result for ${crawlingContext.request.url}`);
|
|
147
|
-
this.stats.trackRenderingTypeMisprediction();
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
crawlingContext.log.debug(`Running browser request handler for ${crawlingContext.request.url}`);
|
|
151
|
-
this.stats.trackBrowserRequestHandlerRun();
|
|
152
|
-
// Run the request handler in a browser. The copy of the crawler state is kept so that we can perform
|
|
153
|
-
// a rendering type detection if necessary. Without this measure, the HTTP request handler would run
|
|
154
|
-
// under different conditions, which could change its behavior. Changes done to the crawler state by
|
|
155
|
-
// the HTTP request handler will not be committed to the actual storage.
|
|
156
|
-
const { result: browserRun, initialStateCopy } = await this.runRequestHandlerInBrowser(crawlingContext);
|
|
157
|
-
if (!browserRun.ok) {
|
|
158
|
-
throw browserRun.error;
|
|
159
|
-
}
|
|
160
|
-
await this.commitResult(crawlingContext, browserRun.result);
|
|
161
312
|
if (shouldDetectRenderingType) {
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
313
|
+
this.inFlightRenderingTypeDetections += 1;
|
|
314
|
+
}
|
|
315
|
+
try {
|
|
316
|
+
if (renderingTypePrediction.renderingType === 'static' && !shouldDetectRenderingType) {
|
|
317
|
+
crawlingContext.log.debug(`Running HTTP-only request handler for ${crawlingContext.request.url}`);
|
|
318
|
+
this.stats.trackHttpOnlyRequestHandlerRun();
|
|
319
|
+
const plainHTTPRun = await this.crawlOne('static', crawlingContext, crawlingContext.useState);
|
|
320
|
+
if (plainHTTPRun.ok && this.resultChecker(plainHTTPRun.result)) {
|
|
321
|
+
crawlingContext.log.debug(`HTTP-only request handler succeeded for ${crawlingContext.request.url}`);
|
|
322
|
+
plainHTTPRun.logs?.forEach(([log, method, ...args]) => log[method](...args));
|
|
323
|
+
await this.commitResult(crawlingContext, plainHTTPRun.result);
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
// Execution will "fall through" and try running the request handler in a browser
|
|
165
327
|
if (!plainHTTPRun.ok) {
|
|
166
|
-
|
|
328
|
+
const actualError = plainHTTPRun.error instanceof RequestHandlerError
|
|
329
|
+
? plainHTTPRun.error.cause
|
|
330
|
+
: plainHTTPRun.error;
|
|
331
|
+
if (await this.shouldPropagateError(actualError, crawlingContext)) {
|
|
332
|
+
throw actualError;
|
|
333
|
+
}
|
|
334
|
+
crawlingContext.log.exception(actualError, `HTTP-only request handler failed for ${crawlingContext.request.url}`);
|
|
335
|
+
}
|
|
336
|
+
else {
|
|
337
|
+
crawlingContext.log.warning(`HTTP-only request handler returned a suspicious result for ${crawlingContext.request.url}`);
|
|
338
|
+
this.stats.trackRenderingTypeMisprediction();
|
|
167
339
|
}
|
|
168
|
-
|
|
169
|
-
|
|
340
|
+
}
|
|
341
|
+
crawlingContext.log.debug(`Running browser request handler for ${crawlingContext.request.url}`);
|
|
342
|
+
this.stats.trackBrowserRequestHandlerRun();
|
|
343
|
+
// Run the request handler in a browser. The copy of the crawler state is kept so that we can perform
|
|
344
|
+
// a rendering type detection if necessary. Without this measure, the HTTP request handler would run
|
|
345
|
+
// under different conditions, which could change its behavior. Changes done to the crawler state by
|
|
346
|
+
// the HTTP request handler will not be committed to the actual storage.
|
|
347
|
+
const stateTracker = {
|
|
348
|
+
stateCopy: null,
|
|
349
|
+
async getLiveState(defaultValue = {}) {
|
|
350
|
+
const state = await crawlingContext.useState(defaultValue);
|
|
351
|
+
if (this.stateCopy === null) {
|
|
352
|
+
this.stateCopy = JSON.parse(JSON.stringify(state));
|
|
353
|
+
}
|
|
354
|
+
return state;
|
|
355
|
+
},
|
|
356
|
+
async getStateCopy(defaultValue = {}) {
|
|
357
|
+
if (this.stateCopy === null) {
|
|
358
|
+
return defaultValue;
|
|
359
|
+
}
|
|
360
|
+
return this.stateCopy;
|
|
361
|
+
},
|
|
362
|
+
};
|
|
363
|
+
const browserRun = await this.crawlOne('clientOnly', crawlingContext, stateTracker.getLiveState.bind(stateTracker));
|
|
364
|
+
if (!browserRun.ok) {
|
|
365
|
+
throw browserRun.error;
|
|
366
|
+
}
|
|
367
|
+
browserRun.logs?.forEach(([log, method, ...args]) => log[method](...args));
|
|
368
|
+
await this.commitResult(crawlingContext, browserRun.result);
|
|
369
|
+
if (shouldDetectRenderingType) {
|
|
370
|
+
crawlingContext.log.debug(`Detecting rendering type for ${crawlingContext.request.url}`);
|
|
371
|
+
const plainHTTPRun = await this.crawlOne('static', crawlingContext, stateTracker.getStateCopy.bind(stateTracker));
|
|
372
|
+
const detectionResult = (() => {
|
|
373
|
+
if (!plainHTTPRun.ok) {
|
|
374
|
+
return 'clientOnly';
|
|
375
|
+
}
|
|
376
|
+
const comparisonResult = this.resultComparator(plainHTTPRun.result, browserRun.result);
|
|
377
|
+
if (comparisonResult === true || comparisonResult === 'equal') {
|
|
378
|
+
return 'static';
|
|
379
|
+
}
|
|
380
|
+
if (comparisonResult === false || comparisonResult === 'different') {
|
|
381
|
+
return 'clientOnly';
|
|
382
|
+
}
|
|
383
|
+
return undefined;
|
|
384
|
+
})();
|
|
385
|
+
crawlingContext.log.debug(`Detected rendering type ${detectionResult} for ${crawlingContext.request.url}`);
|
|
386
|
+
if (detectionResult !== undefined) {
|
|
387
|
+
this.renderingTypePredictor.storeResult(crawlingContext.request, detectionResult);
|
|
170
388
|
}
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
finally {
|
|
392
|
+
if (shouldDetectRenderingType) {
|
|
393
|
+
this.inFlightRenderingTypeDetections -= 1;
|
|
394
|
+
}
|
|
175
395
|
}
|
|
176
396
|
}
|
|
177
397
|
async commitResult(crawlingContext, { calls, keyValueStoreChanges }) {
|
|
178
398
|
await Promise.all([
|
|
179
399
|
...calls.pushData.map(async (params) => crawlingContext.pushData(...params)),
|
|
180
|
-
...calls.enqueueLinks.map(async (params) => await crawlingContext.enqueueLinks(...params)),
|
|
181
400
|
...calls.addRequests.map(async (params) => crawlingContext.addRequests(...params)),
|
|
182
401
|
...Object.entries(keyValueStoreChanges).map(async ([storeIdOrName, changes]) => {
|
|
183
|
-
const store = await crawlingContext.getKeyValueStore(storeIdOrName);
|
|
402
|
+
const store = await crawlingContext.getKeyValueStore({ id: storeIdOrName });
|
|
184
403
|
await Promise.all(Object.entries(changes).map(async ([key, { changedValue, options }]) => store.setValue(key, changedValue, options)));
|
|
185
404
|
}),
|
|
186
405
|
]);
|
|
@@ -188,151 +407,37 @@ export class AdaptivePlaywrightCrawler extends PlaywrightCrawler {
|
|
|
188
407
|
allowStorageAccess(func) {
|
|
189
408
|
return async (...args) => withCheckedStorageAccess(() => { }, async () => func(...args));
|
|
190
409
|
}
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
return async (playwrightContext) => withCheckedStorageAccess(() => {
|
|
199
|
-
if (this.preventDirectStorageAccess) {
|
|
200
|
-
throw new Error('Directly accessing storage in a request handler is not allowed in AdaptivePlaywrightCrawler');
|
|
201
|
-
}
|
|
202
|
-
}, () => this.adaptiveRequestHandler({
|
|
203
|
-
id: crawlingContext.id,
|
|
204
|
-
session: crawlingContext.session,
|
|
205
|
-
proxyInfo: crawlingContext.proxyInfo,
|
|
206
|
-
request: crawlingContext.request,
|
|
207
|
-
response: {
|
|
208
|
-
url: crawlingContext.response.url(),
|
|
209
|
-
statusCode: crawlingContext.response.status(),
|
|
210
|
-
headers: crawlingContext.response.headers(),
|
|
211
|
-
trailers: {},
|
|
212
|
-
complete: true,
|
|
213
|
-
redirectUrls: [],
|
|
214
|
-
},
|
|
215
|
-
log: crawlingContext.log,
|
|
216
|
-
page: crawlingContext.page,
|
|
217
|
-
querySelector: async (selector, timeoutMs = 5_000) => {
|
|
218
|
-
const locator = playwrightContext.page.locator(selector).first();
|
|
219
|
-
await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
|
|
220
|
-
const $ = await playwrightContext.parseWithCheerio();
|
|
221
|
-
return $(selector);
|
|
222
|
-
},
|
|
223
|
-
async waitForSelector(selector, timeoutMs = 5_000) {
|
|
224
|
-
const locator = playwrightContext.page.locator(selector).first();
|
|
225
|
-
await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
|
|
226
|
-
},
|
|
227
|
-
async parseWithCheerio(selector, timeoutMs = 5_000) {
|
|
228
|
-
if (selector) {
|
|
229
|
-
const locator = playwrightContext.page.locator(selector).first();
|
|
230
|
-
await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
|
|
231
|
-
}
|
|
232
|
-
return playwrightContext.parseWithCheerio();
|
|
233
|
-
},
|
|
234
|
-
async enqueueLinks(options = {}, timeoutMs = 5_000) {
|
|
235
|
-
const selector = options.selector ?? 'a';
|
|
236
|
-
const locator = playwrightContext.page.locator(selector).first();
|
|
237
|
-
await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
|
|
238
|
-
const urls = await extractUrlsFromPage(playwrightContext.page, selector, options.baseUrl ??
|
|
239
|
-
playwrightContext.request.loadedUrl ??
|
|
240
|
-
playwrightContext.request.url);
|
|
241
|
-
await result.enqueueLinks({ ...options, urls });
|
|
242
|
-
},
|
|
243
|
-
addRequests: result.addRequests,
|
|
244
|
-
pushData: result.pushData,
|
|
245
|
-
useState: this.allowStorageAccess(async (defaultValue) => {
|
|
246
|
-
const state = await result.useState(defaultValue);
|
|
247
|
-
if (initialStateCopy === undefined) {
|
|
248
|
-
initialStateCopy = JSON.parse(JSON.stringify(state));
|
|
249
|
-
}
|
|
250
|
-
return state;
|
|
251
|
-
}),
|
|
252
|
-
getKeyValueStore: this.allowStorageAccess(result.getKeyValueStore),
|
|
253
|
-
}));
|
|
254
|
-
}
|
|
255
|
-
return Reflect.get(target, propertyName, receiver);
|
|
256
|
-
},
|
|
257
|
-
}), crawlingContext);
|
|
258
|
-
return { result: { result, ok: true }, initialStateCopy };
|
|
259
|
-
}
|
|
260
|
-
catch (error) {
|
|
261
|
-
return { result: { error, ok: false }, initialStateCopy };
|
|
262
|
-
}
|
|
410
|
+
/**
|
|
411
|
+
* Reading the pending request count queries the underlying request manager, which counts as storage access.
|
|
412
|
+
* Since this is internal crawler bookkeeping used to compute the `enqueueLinks` limit (not user-initiated storage
|
|
413
|
+
* access), it must be allowed even while a request handler runs inside the storage-access guard.
|
|
414
|
+
*/
|
|
415
|
+
async getPendingRequestCountApproximation() {
|
|
416
|
+
return this.allowStorageAccess(() => super.getPendingRequestCountApproximation())();
|
|
263
417
|
}
|
|
264
|
-
async
|
|
265
|
-
const
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
pageGotoOptions);
|
|
288
|
-
const response = await crawlingContext.sendRequest({});
|
|
289
|
-
const loadedUrl = response.url;
|
|
290
|
-
crawlingContext.request.loadedUrl = loadedUrl;
|
|
291
|
-
const $ = load(response.body);
|
|
292
|
-
await this.adaptiveRequestHandler({
|
|
293
|
-
...hookContext,
|
|
294
|
-
request: crawlingContext.request,
|
|
295
|
-
response,
|
|
296
|
-
get page() {
|
|
297
|
-
throw new Error('Page object was used in HTTP-only request handler');
|
|
298
|
-
},
|
|
299
|
-
async querySelector(selector, _timeoutMs) {
|
|
300
|
-
return $(selector);
|
|
301
|
-
},
|
|
302
|
-
async waitForSelector(selector, _timeoutMs) {
|
|
303
|
-
if ($(selector).get().length === 0) {
|
|
304
|
-
throw new Error(`Selector '${selector}' not found.`);
|
|
305
|
-
}
|
|
306
|
-
},
|
|
307
|
-
async parseWithCheerio(selector, _timeoutMs) {
|
|
308
|
-
if (selector && $(selector).get().length === 0) {
|
|
309
|
-
throw new Error(`Selector '${selector}' not found.`);
|
|
310
|
-
}
|
|
311
|
-
return $;
|
|
312
|
-
},
|
|
313
|
-
async enqueueLinks(options = {}) {
|
|
314
|
-
const urls = extractUrlsFromCheerio($, options.selector, options.baseUrl ?? loadedUrl);
|
|
315
|
-
await result.enqueueLinks({ ...options, urls });
|
|
316
|
-
},
|
|
317
|
-
addRequests: result.addRequests,
|
|
318
|
-
pushData: result.pushData,
|
|
319
|
-
useState: async (defaultValue) => {
|
|
320
|
-
// return the old state before the browser handler was executed
|
|
321
|
-
// when rerunning the handler via HTTP for detection
|
|
322
|
-
if (oldStateCopy !== undefined) {
|
|
323
|
-
return oldStateCopy ?? defaultValue; // fallback to the default for `null`
|
|
324
|
-
}
|
|
325
|
-
return this.allowStorageAccess(result.useState)(defaultValue);
|
|
326
|
-
},
|
|
327
|
-
getKeyValueStore: this.allowStorageAccess(result.getKeyValueStore),
|
|
328
|
-
});
|
|
329
|
-
await this._executeHooks(this.postNavigationHooks, crawlingContext, pageGotoOptions);
|
|
330
|
-
}, this.requestHandlerTimeoutInnerMillis, 'Request handler timed out'));
|
|
331
|
-
return { result, logs, ok: true };
|
|
332
|
-
}
|
|
333
|
-
catch (error) {
|
|
334
|
-
return { error, logs, ok: false };
|
|
335
|
-
}
|
|
418
|
+
async enqueueLinks(options, request, result) {
|
|
419
|
+
const baseUrl = resolveBaseUrlForEnqueueLinksFiltering({
|
|
420
|
+
enqueueStrategy: options?.strategy,
|
|
421
|
+
finalRequestUrl: request.loadedUrl,
|
|
422
|
+
originalRequestUrl: request.url,
|
|
423
|
+
userProvidedBaseUrl: options?.baseUrl,
|
|
424
|
+
});
|
|
425
|
+
const addRequestsBatched = async (requests) => {
|
|
426
|
+
await result.addRequests(requests);
|
|
427
|
+
return {
|
|
428
|
+
addedRequests: requests.map(({ uniqueKey, id }) => ({
|
|
429
|
+
uniqueKey,
|
|
430
|
+
requestId: id ?? '',
|
|
431
|
+
wasAlreadyPresent: false,
|
|
432
|
+
wasAlreadyHandled: false,
|
|
433
|
+
})),
|
|
434
|
+
waitForAllRequestsToBeAdded: Promise.resolve([]),
|
|
435
|
+
requestsOverLimit: [],
|
|
436
|
+
};
|
|
437
|
+
};
|
|
438
|
+
// We need to use a mock request queue implementation, in order to add the requests into our result object
|
|
439
|
+
const mockRequestQueue = { addRequestsBatched };
|
|
440
|
+
return await this.enqueueLinksWithCrawlDepth({ ...options, baseUrl }, request, mockRequestQueue);
|
|
336
441
|
}
|
|
337
442
|
createLogProxy(log, logs) {
|
|
338
443
|
return new Proxy(log, {
|
|
@@ -346,8 +451,42 @@ export class AdaptivePlaywrightCrawler extends PlaywrightCrawler {
|
|
|
346
451
|
},
|
|
347
452
|
});
|
|
348
453
|
}
|
|
454
|
+
async teardown() {
|
|
455
|
+
await super.teardown();
|
|
456
|
+
for (const hook of this.teardownHooks) {
|
|
457
|
+
await hook();
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
export function createAdaptivePlaywrightRouter(routesOrSchemas) {
|
|
462
|
+
return Router.create(routesOrSchemas);
|
|
349
463
|
}
|
|
350
|
-
|
|
351
|
-
|
|
464
|
+
/**
|
|
465
|
+
* An opt-in {@link AdaptivePlaywrightCrawlerOptions.resultComparator|`resultComparator`} that considers two
|
|
466
|
+
* request handler results equal only if *all* of their observable effects match - the pushed dataset items, the
|
|
467
|
+
* enqueued requests, and the key-value store changes. This is stricter than the default comparator, which only
|
|
468
|
+
* compares dataset items.
|
|
469
|
+
*
|
|
470
|
+
* **Beware:** enqueued URLs are compared exactly. The same page rendered in a browser and via plain HTTP often
|
|
471
|
+
* yields links that differ only in tracking query parameters, for example:
|
|
472
|
+
* - `https://sdk.apify.com/docs/guides/getting-started`
|
|
473
|
+
* - `https://sdk.apify.com/docs/guides/getting-started?__hsfp=1136113150&__hssc=7591405.1.173549427712`
|
|
474
|
+
*
|
|
475
|
+
* Such links are treated as *different*, which will make the crawler favor browser rendering for those pages.
|
|
476
|
+
*
|
|
477
|
+
* **Example usage:**
|
|
478
|
+
* ```ts
|
|
479
|
+
* const crawler = new AdaptivePlaywrightCrawler({
|
|
480
|
+
* resultComparator: fullResultComparator,
|
|
481
|
+
* async requestHandler({ pushData, enqueueLinks }) {
|
|
482
|
+
* // ...
|
|
483
|
+
* },
|
|
484
|
+
* });
|
|
485
|
+
* ```
|
|
486
|
+
*/
|
|
487
|
+
export function fullResultComparator(resultA, resultB) {
|
|
488
|
+
return (isDeepStrictEqual(resultA.datasetItems, resultB.datasetItems) &&
|
|
489
|
+
isDeepStrictEqual(resultA.enqueuedUrls, resultB.enqueuedUrls) &&
|
|
490
|
+
isDeepStrictEqual(resultA.enqueuedUrlLists, resultB.enqueuedUrlLists) &&
|
|
491
|
+
isDeepStrictEqual(resultA.keyValueStoreChanges, resultB.keyValueStoreChanges));
|
|
352
492
|
}
|
|
353
|
-
//# sourceMappingURL=adaptive-playwright-crawler.js.map
|