@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.
- package/README.md +17 -13
- package/index.d.ts +0 -1
- package/index.js +0 -1
- package/internals/adaptive-playwright-crawler.d.ts +81 -58
- package/internals/adaptive-playwright-crawler.js +306 -208
- 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 +9 -6
- package/internals/utils/rendering-type-prediction.js +58 -24
- 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';
|
|
@@ -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,276 @@ 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 waitForSelector() {
|
|
187
|
+
throw new Error(errorMessage('waitForSelector'));
|
|
188
|
+
},
|
|
189
|
+
get parseWithCheerio() {
|
|
190
|
+
throw new Error(errorMessage('parseWithCheerio'));
|
|
191
|
+
},
|
|
192
|
+
}),
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
async adaptCheerioContext(cheerioContext) {
|
|
196
|
+
// Capture the original response to avoid infinite recursion when the getter is copied to the context
|
|
197
|
+
const result = this.resultObjects.get(cheerioContext);
|
|
198
|
+
if (result === undefined) {
|
|
199
|
+
throw new Error('Logical error - `this.resultObjects` does not contain the result object');
|
|
200
|
+
}
|
|
201
|
+
return {
|
|
202
|
+
get page() {
|
|
203
|
+
throw new Error('Page object was used in HTTP-only request handler');
|
|
204
|
+
},
|
|
205
|
+
async querySelector(selector) {
|
|
206
|
+
return cheerioContext.$(selector);
|
|
207
|
+
},
|
|
208
|
+
enqueueLinks: async (options = {}) => {
|
|
209
|
+
const urls = options.urls ??
|
|
210
|
+
extractUrlsFromCheerio(cheerioContext.$, options.selector, options.baseUrl ?? cheerioContext.request.loadedUrl);
|
|
211
|
+
return (await this.enqueueLinks({ ...options, urls }, cheerioContext.request, result));
|
|
212
|
+
},
|
|
213
|
+
response: cheerioContext.response,
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
async adaptPlaywrightContext(playwrightContext) {
|
|
217
|
+
const originalResponse = playwrightContext.response;
|
|
218
|
+
const result = this.resultObjects.get(playwrightContext);
|
|
219
|
+
if (result === undefined) {
|
|
220
|
+
throw new Error('Logical error - `this.resultObjects` does not contain the result object');
|
|
221
|
+
}
|
|
222
|
+
return {
|
|
223
|
+
response: new Response(Uint8Array.from(await originalResponse.body()), {
|
|
224
|
+
headers: originalResponse.headers(),
|
|
225
|
+
status: originalResponse.status(),
|
|
226
|
+
statusText: originalResponse.statusText(),
|
|
227
|
+
}),
|
|
228
|
+
async querySelector(selector, timeoutMs = 5000) {
|
|
229
|
+
const locator = playwrightContext.page.locator(selector).first();
|
|
230
|
+
await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
|
|
231
|
+
const $ = await playwrightContext.parseWithCheerio();
|
|
232
|
+
return $(selector);
|
|
233
|
+
},
|
|
234
|
+
enqueueLinks: async (options = {}, timeoutMs = 5000) => {
|
|
235
|
+
// TODO consider using `context.parseWithCheerio` to make this universal and avoid code duplication
|
|
236
|
+
let urls;
|
|
237
|
+
if (options.urls === undefined) {
|
|
238
|
+
const selector = options.selector ?? 'a';
|
|
239
|
+
const locator = playwrightContext.page.locator(selector).first();
|
|
240
|
+
await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
|
|
241
|
+
urls =
|
|
242
|
+
options.urls ??
|
|
243
|
+
(await extractUrlsFromPage(playwrightContext.page, selector, options.baseUrl ?? playwrightContext.request.loadedUrl));
|
|
244
|
+
}
|
|
245
|
+
else {
|
|
246
|
+
urls = options.urls;
|
|
247
|
+
}
|
|
248
|
+
return (await this.enqueueLinks({ ...options, urls }, playwrightContext.request, result));
|
|
249
|
+
},
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
async crawlOne(renderingType, context, useStateFunction) {
|
|
253
|
+
const result = new RequestHandlerResult(serviceLocator.getConfiguration(), AdaptivePlaywrightCrawler.CRAWLEE_STATE_KEY);
|
|
254
|
+
const logs = [];
|
|
255
|
+
const deferredCleanup = [];
|
|
256
|
+
const resultBoundContextHelpers = {
|
|
257
|
+
addRequests: result.addRequests,
|
|
258
|
+
pushData: result.pushData,
|
|
259
|
+
useState: this.allowStorageAccess(useStateFunction),
|
|
260
|
+
getKeyValueStore: this.allowStorageAccess(result.getKeyValueStore),
|
|
261
|
+
log: this.createLogProxy(context.log, logs),
|
|
262
|
+
registerDeferredCleanup: (cleanup) => deferredCleanup.push(cleanup),
|
|
263
|
+
};
|
|
264
|
+
const subCrawlerContext = Object.defineProperties({}, Object.getOwnPropertyDescriptors(context));
|
|
265
|
+
// Mark result-bound helpers as non-configurable so they survive the sub-crawler context pipeline
|
|
266
|
+
// (which would otherwise override them with the sub-crawler's own versions, losing the result binding).
|
|
267
|
+
for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(resultBoundContextHelpers))) {
|
|
268
|
+
Object.defineProperty(subCrawlerContext, key, { ...descriptor, configurable: false });
|
|
269
|
+
}
|
|
270
|
+
this.resultObjects.set(subCrawlerContext, result);
|
|
271
|
+
try {
|
|
272
|
+
const callAdaptiveRequestHandler = async () => {
|
|
273
|
+
if (renderingType === 'static') {
|
|
274
|
+
await this.staticContextPipeline.call(subCrawlerContext, this.requestHandler.bind(this));
|
|
275
|
+
}
|
|
276
|
+
else if (renderingType === 'clientOnly') {
|
|
277
|
+
await this.browserContextPipeline.call(subCrawlerContext, this.requestHandler.bind(this));
|
|
278
|
+
}
|
|
279
|
+
};
|
|
280
|
+
await addTimeoutToPromise(async () => withCheckedStorageAccess(() => {
|
|
281
|
+
if (this.preventDirectStorageAccess) {
|
|
282
|
+
throw new Error('Directly accessing storage in a request handler is not allowed in AdaptivePlaywrightCrawler');
|
|
283
|
+
}
|
|
284
|
+
}, callAdaptiveRequestHandler), this.individualRequestHandlerTimeoutMillis, 'Request handler timed out');
|
|
285
|
+
return { result, ok: true, logs };
|
|
286
|
+
}
|
|
287
|
+
catch (error) {
|
|
288
|
+
return { error, ok: false, logs };
|
|
289
|
+
}
|
|
290
|
+
finally {
|
|
291
|
+
await Promise.all(deferredCleanup.map((cleanup) => cleanup()));
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
async runRequestHandler(crawlingContext) {
|
|
127
295
|
const renderingTypePrediction = this.renderingTypePredictor.predict(crawlingContext.request);
|
|
128
296
|
const shouldDetectRenderingType = Math.random() < renderingTypePrediction.detectionProbabilityRecommendation;
|
|
129
297
|
if (!shouldDetectRenderingType) {
|
|
130
298
|
crawlingContext.log.debug(`Predicted rendering type ${renderingTypePrediction.renderingType} for ${crawlingContext.request.url}`);
|
|
131
299
|
}
|
|
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
300
|
if (shouldDetectRenderingType) {
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
301
|
+
this.inFlightRenderingTypeDetections += 1;
|
|
302
|
+
}
|
|
303
|
+
try {
|
|
304
|
+
if (renderingTypePrediction.renderingType === 'static' && !shouldDetectRenderingType) {
|
|
305
|
+
crawlingContext.log.debug(`Running HTTP-only request handler for ${crawlingContext.request.url}`);
|
|
306
|
+
this.stats.trackHttpOnlyRequestHandlerRun();
|
|
307
|
+
const plainHTTPRun = await this.crawlOne('static', crawlingContext, crawlingContext.useState);
|
|
308
|
+
if (plainHTTPRun.ok && this.resultChecker(plainHTTPRun.result)) {
|
|
309
|
+
crawlingContext.log.debug(`HTTP-only request handler succeeded for ${crawlingContext.request.url}`);
|
|
310
|
+
plainHTTPRun.logs?.forEach(([log, method, ...args]) => log[method](...args));
|
|
311
|
+
await this.commitResult(crawlingContext, plainHTTPRun.result);
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
// Execution will "fall through" and try running the request handler in a browser
|
|
165
315
|
if (!plainHTTPRun.ok) {
|
|
166
|
-
|
|
316
|
+
const actualError = plainHTTPRun.error instanceof RequestHandlerError
|
|
317
|
+
? plainHTTPRun.error.cause
|
|
318
|
+
: plainHTTPRun.error;
|
|
319
|
+
if (await this.shouldPropagateError(actualError, crawlingContext)) {
|
|
320
|
+
throw actualError;
|
|
321
|
+
}
|
|
322
|
+
crawlingContext.log.exception(actualError, `HTTP-only request handler failed for ${crawlingContext.request.url}`);
|
|
323
|
+
}
|
|
324
|
+
else {
|
|
325
|
+
crawlingContext.log.warning(`HTTP-only request handler returned a suspicious result for ${crawlingContext.request.url}`);
|
|
326
|
+
this.stats.trackRenderingTypeMisprediction();
|
|
167
327
|
}
|
|
168
|
-
|
|
169
|
-
|
|
328
|
+
}
|
|
329
|
+
crawlingContext.log.debug(`Running browser request handler for ${crawlingContext.request.url}`);
|
|
330
|
+
this.stats.trackBrowserRequestHandlerRun();
|
|
331
|
+
// Run the request handler in a browser. The copy of the crawler state is kept so that we can perform
|
|
332
|
+
// a rendering type detection if necessary. Without this measure, the HTTP request handler would run
|
|
333
|
+
// under different conditions, which could change its behavior. Changes done to the crawler state by
|
|
334
|
+
// the HTTP request handler will not be committed to the actual storage.
|
|
335
|
+
const stateTracker = {
|
|
336
|
+
stateCopy: null,
|
|
337
|
+
async getLiveState(defaultValue = {}) {
|
|
338
|
+
const state = await crawlingContext.useState(defaultValue);
|
|
339
|
+
if (this.stateCopy === null) {
|
|
340
|
+
this.stateCopy = JSON.parse(JSON.stringify(state));
|
|
341
|
+
}
|
|
342
|
+
return state;
|
|
343
|
+
},
|
|
344
|
+
async getStateCopy(defaultValue = {}) {
|
|
345
|
+
if (this.stateCopy === null) {
|
|
346
|
+
return defaultValue;
|
|
347
|
+
}
|
|
348
|
+
return this.stateCopy;
|
|
349
|
+
},
|
|
350
|
+
};
|
|
351
|
+
const browserRun = await this.crawlOne('clientOnly', crawlingContext, stateTracker.getLiveState.bind(stateTracker));
|
|
352
|
+
if (!browserRun.ok) {
|
|
353
|
+
throw browserRun.error;
|
|
354
|
+
}
|
|
355
|
+
browserRun.logs?.forEach(([log, method, ...args]) => log[method](...args));
|
|
356
|
+
await this.commitResult(crawlingContext, browserRun.result);
|
|
357
|
+
if (shouldDetectRenderingType) {
|
|
358
|
+
crawlingContext.log.debug(`Detecting rendering type for ${crawlingContext.request.url}`);
|
|
359
|
+
const plainHTTPRun = await this.crawlOne('static', crawlingContext, stateTracker.getStateCopy.bind(stateTracker));
|
|
360
|
+
const detectionResult = (() => {
|
|
361
|
+
if (!plainHTTPRun.ok) {
|
|
362
|
+
return 'clientOnly';
|
|
363
|
+
}
|
|
364
|
+
const comparisonResult = this.resultComparator(plainHTTPRun.result, browserRun.result);
|
|
365
|
+
if (comparisonResult === true || comparisonResult === 'equal') {
|
|
366
|
+
return 'static';
|
|
367
|
+
}
|
|
368
|
+
if (comparisonResult === false || comparisonResult === 'different') {
|
|
369
|
+
return 'clientOnly';
|
|
370
|
+
}
|
|
371
|
+
return undefined;
|
|
372
|
+
})();
|
|
373
|
+
crawlingContext.log.debug(`Detected rendering type ${detectionResult} for ${crawlingContext.request.url}`);
|
|
374
|
+
if (detectionResult !== undefined) {
|
|
375
|
+
this.renderingTypePredictor.storeResult(crawlingContext.request, detectionResult);
|
|
170
376
|
}
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
finally {
|
|
380
|
+
if (shouldDetectRenderingType) {
|
|
381
|
+
this.inFlightRenderingTypeDetections -= 1;
|
|
382
|
+
}
|
|
175
383
|
}
|
|
176
384
|
}
|
|
177
385
|
async commitResult(crawlingContext, { calls, keyValueStoreChanges }) {
|
|
178
386
|
await Promise.all([
|
|
179
387
|
...calls.pushData.map(async (params) => crawlingContext.pushData(...params)),
|
|
180
|
-
...calls.enqueueLinks.map(async (params) => await crawlingContext.enqueueLinks(...params)),
|
|
181
388
|
...calls.addRequests.map(async (params) => crawlingContext.addRequests(...params)),
|
|
182
389
|
...Object.entries(keyValueStoreChanges).map(async ([storeIdOrName, changes]) => {
|
|
183
|
-
const store = await crawlingContext.getKeyValueStore(storeIdOrName);
|
|
390
|
+
const store = await crawlingContext.getKeyValueStore({ id: storeIdOrName });
|
|
184
391
|
await Promise.all(Object.entries(changes).map(async ([key, { changedValue, options }]) => store.setValue(key, changedValue, options)));
|
|
185
392
|
}),
|
|
186
393
|
]);
|
|
@@ -188,151 +395,37 @@ export class AdaptivePlaywrightCrawler extends PlaywrightCrawler {
|
|
|
188
395
|
allowStorageAccess(func) {
|
|
189
396
|
return async (...args) => withCheckedStorageAccess(() => { }, async () => func(...args));
|
|
190
397
|
}
|
|
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
|
-
}
|
|
398
|
+
/**
|
|
399
|
+
* Reading the pending request count queries the underlying request manager, which counts as storage access.
|
|
400
|
+
* Since this is internal crawler bookkeeping used to compute the `enqueueLinks` limit (not user-initiated storage
|
|
401
|
+
* access), it must be allowed even while a request handler runs inside the storage-access guard.
|
|
402
|
+
*/
|
|
403
|
+
async getPendingRequestCountApproximation() {
|
|
404
|
+
return this.allowStorageAccess(() => super.getPendingRequestCountApproximation())();
|
|
263
405
|
}
|
|
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
|
-
}
|
|
406
|
+
async enqueueLinks(options, request, result) {
|
|
407
|
+
const baseUrl = resolveBaseUrlForEnqueueLinksFiltering({
|
|
408
|
+
enqueueStrategy: options?.strategy,
|
|
409
|
+
finalRequestUrl: request.loadedUrl,
|
|
410
|
+
originalRequestUrl: request.url,
|
|
411
|
+
userProvidedBaseUrl: options?.baseUrl,
|
|
412
|
+
});
|
|
413
|
+
const addRequestsBatched = async (requests) => {
|
|
414
|
+
await result.addRequests(requests);
|
|
415
|
+
return {
|
|
416
|
+
addedRequests: requests.map(({ uniqueKey, id }) => ({
|
|
417
|
+
uniqueKey,
|
|
418
|
+
requestId: id ?? '',
|
|
419
|
+
wasAlreadyPresent: false,
|
|
420
|
+
wasAlreadyHandled: false,
|
|
421
|
+
})),
|
|
422
|
+
waitForAllRequestsToBeAdded: Promise.resolve([]),
|
|
423
|
+
requestsOverLimit: [],
|
|
424
|
+
};
|
|
425
|
+
};
|
|
426
|
+
// We need to use a mock request queue implementation, in order to add the requests into our result object
|
|
427
|
+
const mockRequestQueue = { addRequestsBatched };
|
|
428
|
+
return await this.enqueueLinksWithCrawlDepth({ ...options, baseUrl }, request, mockRequestQueue);
|
|
336
429
|
}
|
|
337
430
|
createLogProxy(log, logs) {
|
|
338
431
|
return new Proxy(log, {
|
|
@@ -346,8 +439,13 @@ export class AdaptivePlaywrightCrawler extends PlaywrightCrawler {
|
|
|
346
439
|
},
|
|
347
440
|
});
|
|
348
441
|
}
|
|
442
|
+
async teardown() {
|
|
443
|
+
await super.teardown();
|
|
444
|
+
for (const hook of this.teardownHooks) {
|
|
445
|
+
await hook();
|
|
446
|
+
}
|
|
447
|
+
}
|
|
349
448
|
}
|
|
350
|
-
export function createAdaptivePlaywrightRouter(
|
|
351
|
-
return Router.create(
|
|
449
|
+
export function createAdaptivePlaywrightRouter(routesOrSchemas) {
|
|
450
|
+
return Router.create(routesOrSchemas);
|
|
352
451
|
}
|
|
353
|
-
//# sourceMappingURL=adaptive-playwright-crawler.js.map
|