@crawlee/playwright 4.0.0-rc.1 → 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.
- package/internals/adaptive-playwright-crawler.d.ts +24 -13
- package/internals/adaptive-playwright-crawler.js +153 -85
- package/internals/playwright-browser-pool.d.ts +12 -28
- package/internals/playwright-browser-pool.js +0 -27
- package/internals/playwright-crawler.d.ts +3 -0
- package/internals/playwright-crawler.js +20 -10
- package/internals/playwright-launcher.js +2 -1
- package/internals/utils/playwright-utils.d.ts +11 -1
- package/internals/utils/rendering-type-prediction.d.ts +2 -5
- package/internals/utils/rendering-type-prediction.js +0 -2
- package/package.json +15 -13
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import type { BrowserHook, LoadedRequest,
|
|
1
|
+
import type { BrowserHook, LoadedRequest, RouterHandler, RouteSchemas, RoutesFromSchemas } from '@crawlee/browser';
|
|
2
2
|
import type { BasicCrawlerOptions, CrawlingContext, EnqueueLinksOptions, GetUserDataFromRequest, RouterRoutes } from '@crawlee/basic';
|
|
3
3
|
import { BasicCrawler } from '@crawlee/basic';
|
|
4
|
+
import { CrawlingRequest } from '@crawlee/browser';
|
|
4
5
|
import type { StorageTransactionView } from '@crawlee/core';
|
|
5
6
|
import type { Dictionary, Awaitable } from '@crawlee/types';
|
|
6
7
|
import { type Cheerio, type CheerioAPI } from 'cheerio';
|
|
@@ -43,16 +44,17 @@ export interface AdaptivePlaywrightCrawlerContext<UserData extends Dictionary =
|
|
|
43
44
|
* Playwright Page object. If accessed in HTTP-only rendering, this will throw an error and make the AdaptivePlaywrightCrawlerContext retry the request in a browser.
|
|
44
45
|
*/
|
|
45
46
|
page: Page;
|
|
46
|
-
/**
|
|
47
|
-
* Wait for an element matching the selector to appear and return a Cheerio object of the first matched element.
|
|
48
|
-
* Timeout defaults to 5s.
|
|
49
|
-
*/
|
|
50
|
-
querySelector(selector: string, timeoutMs?: number): Promise<Cheerio<AnyNode>>;
|
|
51
47
|
/**
|
|
52
48
|
* Wait for an element matching the selector to appear and return a Cheerio object of all matched elements.
|
|
49
|
+
* Throws when nothing matches - in the HTTP-only run, that makes the crawler retry the request in a browser.
|
|
53
50
|
* Timeout defaults to 5s.
|
|
54
51
|
*/
|
|
55
52
|
querySelectorAll(selector: string, timeoutMs?: number): Promise<Cheerio<AnyNode>>;
|
|
53
|
+
/**
|
|
54
|
+
* Like {@link AdaptivePlaywrightCrawlerContext.querySelectorAll|`querySelectorAll`}, but returns only the
|
|
55
|
+
* first match.
|
|
56
|
+
*/
|
|
57
|
+
querySelectorOne(selector: string, timeoutMs?: number): Promise<Cheerio<AnyNode>>;
|
|
56
58
|
/**
|
|
57
59
|
* Wait for an element matching the selector to appear.
|
|
58
60
|
* Timeout defaults to 5s.
|
|
@@ -82,7 +84,7 @@ export interface AdaptivePlaywrightCrawlerContext<UserData extends Dictionary =
|
|
|
82
84
|
parseWithCheerio(selector?: string, timeoutMs?: number): Promise<CheerioAPI>;
|
|
83
85
|
enqueueLinks(options?: EnqueueLinksOptions): Promise<unknown>;
|
|
84
86
|
}
|
|
85
|
-
interface AdaptiveHookContext extends Pick<AdaptivePlaywrightCrawlerContext, 'id' | 'session' | 'proxyInfo' | 'log'> {
|
|
87
|
+
interface AdaptiveHookContext extends Pick<AdaptivePlaywrightCrawlerContext, 'id' | 'session' | 'proxyInfo' | 'log' | 'extendTimeout'> {
|
|
86
88
|
page?: Page;
|
|
87
89
|
request: CrawlingRequest;
|
|
88
90
|
gotoOptions?: PlaywrightGotoOptions;
|
|
@@ -91,7 +93,18 @@ type AdaptiveHook<ContextExtension = Dictionary<never>> = BrowserHook<AdaptiveHo
|
|
|
91
93
|
type AdaptivePostNavigationHook<ContextExtension = Dictionary<never>> = BrowserHook<Omit<AdaptiveHookContext, 'request'> & {
|
|
92
94
|
request: LoadedRequest<CrawlingRequest>;
|
|
93
95
|
}, ContextExtension>;
|
|
96
|
+
/** Passed to {@link AdaptivePlaywrightCrawlerOptions.resultChecker} and `resultComparator` alongside the results. */
|
|
97
|
+
export interface AdaptiveResultContext {
|
|
98
|
+
/** The request whose handler produced the results. */
|
|
99
|
+
request: CrawlingRequest;
|
|
100
|
+
}
|
|
94
101
|
export interface AdaptivePlaywrightCrawlerOptions<ContextExtension = Dictionary<never>, ExtendedContext extends AdaptivePlaywrightCrawlerContext = AdaptivePlaywrightCrawlerContext & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<AdaptivePlaywrightCrawlerContext['request']>>, StatisticStateExtension extends AdaptivePlaywrightCrawlerStatisticState = AdaptivePlaywrightCrawlerStatisticState> extends Omit<BasicCrawlerOptions<AdaptivePlaywrightCrawlerContext, ContextExtension, ExtendedContext, Routes, StatisticStateExtension>, 'preNavigationHooks' | 'postNavigationHooks' | 'contextPipelineBuilder'>, Pick<PlaywrightCrawlerOptions, 'launchContext' | 'headless' | 'browserPool' | 'remoteBrowser'> {
|
|
102
|
+
/**
|
|
103
|
+
* Timeout for the navigation phase of each attempt, in seconds, shared by the `preNavigationHooks`, the
|
|
104
|
+
* navigation and the `postNavigationHooks`. Applies to both the HTTP-only and the browser attempt. When not
|
|
105
|
+
* set, each attempt keeps its own default: 30 seconds for HTTP-only and 60 seconds for the browser.
|
|
106
|
+
*/
|
|
107
|
+
navigationTimeoutSecs?: number;
|
|
95
108
|
/**
|
|
96
109
|
* Async functions that are sequentially evaluated before the navigation. Good for setting additional cookies.
|
|
97
110
|
* The function accepts a subset of the crawling context. If you attempt to access the `page` property during HTTP-only crawling,
|
|
@@ -121,7 +134,7 @@ export interface AdaptivePlaywrightCrawlerOptions<ContextExtension = Dictionary<
|
|
|
121
134
|
* If it returns false, the request is retried in a browser.
|
|
122
135
|
* If no callback is specified, every result is considered valid.
|
|
123
136
|
*/
|
|
124
|
-
resultChecker?: (result: StorageTransactionView) => boolean;
|
|
137
|
+
resultChecker?: (result: StorageTransactionView, context: AdaptiveResultContext) => boolean;
|
|
125
138
|
/**
|
|
126
139
|
* An optional callback that decides whether an error thrown during the plain HTTP request handler
|
|
127
140
|
* should be propagated (instead of falling back to browser navigation).
|
|
@@ -144,7 +157,7 @@ export interface AdaptivePlaywrightCrawlerOptions<ContextExtension = Dictionary<
|
|
|
144
157
|
*
|
|
145
158
|
* For a stricter, ready-made comparator that also takes enqueued requests and key-value store changes into account, see {@link fullResultComparator}.
|
|
146
159
|
*/
|
|
147
|
-
resultComparator?: (resultA: StorageTransactionView, resultB: StorageTransactionView) => boolean | 'equal' | 'different' | 'inconclusive';
|
|
160
|
+
resultComparator?: (resultA: StorageTransactionView, resultB: StorageTransactionView, context: AdaptiveResultContext) => boolean | 'equal' | 'different' | 'inconclusive';
|
|
148
161
|
/**
|
|
149
162
|
* A custom rendering type predictor. A predictor passed here is borrowed - the crawler never drives its
|
|
150
163
|
* lifecycle, so set it up yourself (the built-in {@link RenderingTypePredictor} needs `initialize()`).
|
|
@@ -160,9 +173,9 @@ export interface AdaptivePlaywrightCrawlerOptions<ContextExtension = Dictionary<
|
|
|
160
173
|
* ```javascript
|
|
161
174
|
* const crawler = new AdaptivePlaywrightCrawler({
|
|
162
175
|
* renderingTypeDetectionRatio: 0.1,
|
|
163
|
-
* async requestHandler({
|
|
176
|
+
* async requestHandler({ querySelectorAll, pushData, enqueueLinks, request, log }) {
|
|
164
177
|
* // This function is called to extract data from a single web page
|
|
165
|
-
* const $prices = await
|
|
178
|
+
* const $prices = await querySelectorAll('span.price')
|
|
166
179
|
*
|
|
167
180
|
* await pushData({
|
|
168
181
|
* url: request.url,
|
|
@@ -178,8 +191,6 @@ export interface AdaptivePlaywrightCrawlerOptions<ContextExtension = Dictionary<
|
|
|
178
191
|
* 'http://www.example.com/page-2',
|
|
179
192
|
* ]);
|
|
180
193
|
* ```
|
|
181
|
-
*
|
|
182
|
-
* @experimental
|
|
183
194
|
*/
|
|
184
195
|
export declare class AdaptivePlaywrightCrawler<ContextExtension = Dictionary<never>, ExtendedContext extends AdaptivePlaywrightCrawlerContext = AdaptivePlaywrightCrawlerContext & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<AdaptivePlaywrightCrawlerContext['request']>>, StatisticStateExtension extends AdaptivePlaywrightCrawlerStatisticState = AdaptivePlaywrightCrawlerStatisticState> extends BasicCrawler<AdaptivePlaywrightCrawlerContext, ContextExtension, ExtendedContext, Routes, StatisticStateExtension> {
|
|
185
196
|
#private;
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
2
2
|
import { isDeepStrictEqual } from 'node:util';
|
|
3
|
-
import { BasicCrawler, ContextPipeline, ContextPipelineInitializationError, ContextPipelineInterruptedError, RequestHandlerError, resolveBaseUrlForEnqueueLinksFiltering, Router, Statistics, } from '@crawlee/basic';
|
|
4
|
-
import { extractUrlsFromPage } from '@crawlee/browser';
|
|
3
|
+
import { BasicCrawler, ContextPipeline, ContextPipelineInitializationError, ContextPipelineInterruptedError, navigationDeadlineKey, RequestHandlerError, resolveBaseUrlForEnqueueLinksFiltering, Router, Statistics, } from '@crawlee/basic';
|
|
4
|
+
import { CrawlingRequest, extractUrlsFromPage } from '@crawlee/browser';
|
|
5
5
|
import { CheerioCrawler } from '@crawlee/cheerio';
|
|
6
|
+
import { ResponseWithUrl } from '@crawlee/http-client';
|
|
6
7
|
import { createStorageTransaction, EnqueueStrategy, OwnedOrInjected } from '@crawlee/core';
|
|
7
|
-
import { extractUrlsFromCheerio, parseArgument } from '@crawlee/utils/internal';
|
|
8
|
+
import { extractUrlsFromCheerio, MutationJournal, parseArgument } from '@crawlee/utils/internal';
|
|
8
9
|
import { z } from 'zod';
|
|
9
10
|
import { addTimeoutToPromise } from '@apify/timeout';
|
|
10
11
|
import { PlaywrightCrawler } from './playwright-crawler.js';
|
|
@@ -43,9 +44,9 @@ const proxyLogMethods = [
|
|
|
43
44
|
* ```javascript
|
|
44
45
|
* const crawler = new AdaptivePlaywrightCrawler({
|
|
45
46
|
* renderingTypeDetectionRatio: 0.1,
|
|
46
|
-
* async requestHandler({
|
|
47
|
+
* async requestHandler({ querySelectorAll, pushData, enqueueLinks, request, log }) {
|
|
47
48
|
* // This function is called to extract data from a single web page
|
|
48
|
-
* const $prices = await
|
|
49
|
+
* const $prices = await querySelectorAll('span.price')
|
|
49
50
|
*
|
|
50
51
|
* await pushData({
|
|
51
52
|
* url: request.url,
|
|
@@ -61,8 +62,6 @@ const proxyLogMethods = [
|
|
|
61
62
|
* 'http://www.example.com/page-2',
|
|
62
63
|
* ]);
|
|
63
64
|
* ```
|
|
64
|
-
*
|
|
65
|
-
* @experimental
|
|
66
65
|
*/
|
|
67
66
|
export class AdaptivePlaywrightCrawler extends BasicCrawler {
|
|
68
67
|
#renderingTypePredictor;
|
|
@@ -90,7 +89,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
|
|
|
90
89
|
*/
|
|
91
90
|
#shutDown = false;
|
|
92
91
|
constructor(options = {}) {
|
|
93
|
-
const { requestHandler, renderingTypeDetectionRatio = 0.1, renderingTypePredictor, resultChecker, shouldPropagateError, resultComparator, statistics, requestHandlerTimeoutSecs = 60, errorHandler, failedRequestHandler, preNavigationHooks = [], postNavigationHooks = [], extendContext, transactionalStorage, launchContext, headless, browserPool, remoteBrowser, ...rest } = options;
|
|
92
|
+
const { requestHandler, renderingTypeDetectionRatio = 0.1, renderingTypePredictor, resultChecker, shouldPropagateError, resultComparator, statistics, requestHandlerTimeoutSecs = 60, errorHandler, failedRequestHandler, preNavigationHooks = [], postNavigationHooks = [], extendContext, transactionalStorage, navigationTimeoutSecs, launchContext, headless, browserPool, remoteBrowser, ...rest } = options;
|
|
94
93
|
// The user's value is replaced by `false` in the `super` call below — validate it separately,
|
|
95
94
|
// wrapped in an object so the error still names the field.
|
|
96
95
|
parseArgument({ transactionalStorage }, z.object({ transactionalStorage: BasicCrawler.optionsShape.transactionalStorage }), 'AdaptivePlaywrightCrawlerOptions');
|
|
@@ -146,7 +145,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
|
|
|
146
145
|
this.#resultComparator = resultComparator;
|
|
147
146
|
}
|
|
148
147
|
else if (resultChecker !== undefined) {
|
|
149
|
-
this.#resultComparator = (resultA, resultB) => this.#resultChecker(resultA) && this.#resultChecker(resultB);
|
|
148
|
+
this.#resultComparator = (resultA, resultB, context) => this.#resultChecker(resultA, context) && this.#resultChecker(resultB, context);
|
|
150
149
|
}
|
|
151
150
|
else {
|
|
152
151
|
this.#resultComparator = (resultA, resultB) => {
|
|
@@ -171,6 +170,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
|
|
|
171
170
|
preNavigationHooks,
|
|
172
171
|
postNavigationHooks,
|
|
173
172
|
extendContext,
|
|
173
|
+
navigationTimeoutSecs,
|
|
174
174
|
});
|
|
175
175
|
const browserCrawler = new PlaywrightCrawler({
|
|
176
176
|
...rest,
|
|
@@ -178,6 +178,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
|
|
|
178
178
|
preNavigationHooks: preNavigationHooks,
|
|
179
179
|
postNavigationHooks: postNavigationHooks,
|
|
180
180
|
extendContext,
|
|
181
|
+
navigationTimeoutSecs,
|
|
181
182
|
launchContext,
|
|
182
183
|
headless,
|
|
183
184
|
browserPool,
|
|
@@ -185,8 +186,26 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
|
|
|
185
186
|
});
|
|
186
187
|
this.#staticCrawler = staticCrawler;
|
|
187
188
|
this.#browserCrawler = browserCrawler;
|
|
188
|
-
|
|
189
|
-
|
|
189
|
+
// Each attempt needs its own deferred cleanups, and they must share the attempt's cleanup stack: resources the
|
|
190
|
+
// pipeline defers releasing (the page) have to outlive the user's cleanups, which may still use them.
|
|
191
|
+
const deferredCleanup = ContextPipeline.create().compose((_context, onCleanup) => ({
|
|
192
|
+
registerDeferredCleanup: (cleanup) => {
|
|
193
|
+
onCleanup(async () => {
|
|
194
|
+
try {
|
|
195
|
+
await cleanup();
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
this.log.debug('Error in deferred cleanup', { error });
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
},
|
|
202
|
+
}));
|
|
203
|
+
this.#staticContextPipeline = deferredCleanup
|
|
204
|
+
.chain(staticCrawler.contextPipeline)
|
|
205
|
+
.compose(this.#adaptCheerioContext.bind(this));
|
|
206
|
+
this.#browserContextPipeline = deferredCleanup
|
|
207
|
+
.chain(browserCrawler.contextPipeline)
|
|
208
|
+
.compose(this.#adaptPlaywrightContext.bind(this));
|
|
190
209
|
}
|
|
191
210
|
async init() {
|
|
192
211
|
// A crawler can be run again after a teardown.
|
|
@@ -208,12 +227,12 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
|
|
|
208
227
|
get page() {
|
|
209
228
|
throw new Error(errorMessage('page'));
|
|
210
229
|
},
|
|
211
|
-
get querySelector() {
|
|
212
|
-
throw new Error(errorMessage('querySelector'));
|
|
213
|
-
},
|
|
214
230
|
get querySelectorAll() {
|
|
215
231
|
throw new Error(errorMessage('querySelectorAll'));
|
|
216
232
|
},
|
|
233
|
+
get querySelectorOne() {
|
|
234
|
+
throw new Error(errorMessage('querySelectorOne'));
|
|
235
|
+
},
|
|
217
236
|
get waitForSelector() {
|
|
218
237
|
throw new Error(errorMessage('waitForSelector'));
|
|
219
238
|
},
|
|
@@ -230,45 +249,39 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
|
|
|
230
249
|
get page() {
|
|
231
250
|
throw new Error('Page object was used in HTTP-only request handler');
|
|
232
251
|
},
|
|
233
|
-
async querySelector(selector) {
|
|
234
|
-
return cheerioContext.$(selector).first();
|
|
235
|
-
},
|
|
236
|
-
async querySelectorAll(selector) {
|
|
237
|
-
return cheerioContext.$(selector);
|
|
238
|
-
},
|
|
239
252
|
enqueueLinks: async (options = {}) => {
|
|
240
253
|
const urls = extractUrlsFromCheerio(cheerioContext.$, options.selector, options.baseUrl ?? cheerioContext.request.loadedUrl);
|
|
241
254
|
return (await this.#enqueueLinks(urls, options, cheerioContext.request));
|
|
242
255
|
},
|
|
243
|
-
|
|
256
|
+
// The HTTP crawler has already consumed the body; hand out a fresh copy, like the browser side does.
|
|
257
|
+
// HTML bodies are already decoded to UTF-8, so `arrayBuffer()` may disagree with the original headers.
|
|
258
|
+
response: new ResponseWithUrl(cheerioContext.body, cheerioContext.response),
|
|
244
259
|
};
|
|
245
260
|
}
|
|
246
261
|
async #adaptPlaywrightContext(playwrightContext) {
|
|
247
262
|
// Capture the original response to avoid infinite recursion when the getter is copied to the context
|
|
248
263
|
const originalResponse = playwrightContext.response;
|
|
264
|
+
// `headers()` can return repeated headers (e.g. `set-cookie`) joined with `\n`, which `Headers` rejects
|
|
265
|
+
const headers = new Headers();
|
|
266
|
+
for (const { name, value } of await originalResponse.headersArray()) {
|
|
267
|
+
headers.append(name, value);
|
|
268
|
+
}
|
|
249
269
|
return {
|
|
250
|
-
response: new
|
|
251
|
-
headers
|
|
270
|
+
response: new ResponseWithUrl(Uint8Array.from(await originalResponse.body()), {
|
|
271
|
+
headers,
|
|
252
272
|
status: originalResponse.status(),
|
|
253
273
|
statusText: originalResponse.statusText(),
|
|
274
|
+
url: originalResponse.url(),
|
|
254
275
|
}),
|
|
255
|
-
async querySelector(selector, timeoutMs = 5000) {
|
|
256
|
-
const locator = playwrightContext.page.locator(selector).first();
|
|
257
|
-
await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
|
|
258
|
-
const $ = await playwrightContext.parseWithCheerio();
|
|
259
|
-
return $(selector).first();
|
|
260
|
-
},
|
|
261
|
-
async querySelectorAll(selector, timeoutMs = 5000) {
|
|
262
|
-
const locator = playwrightContext.page.locator(selector).first();
|
|
263
|
-
await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
|
|
264
|
-
const $ = await playwrightContext.parseWithCheerio();
|
|
265
|
-
return $(selector);
|
|
266
|
-
},
|
|
267
276
|
enqueueLinks: async (options = {}, timeoutMs = 5000) => {
|
|
268
277
|
// TODO consider using `context.parseWithCheerio` to make this universal and avoid code duplication
|
|
269
278
|
const selector = options.selector ?? 'a';
|
|
270
279
|
const locator = playwrightContext.page.locator(selector).first();
|
|
271
|
-
|
|
280
|
+
// Wait for client-rendered links, but like the HTTP side, enqueue nothing when there are none.
|
|
281
|
+
await locator.waitFor({ timeout: timeoutMs, state: 'attached' }).catch((error) => {
|
|
282
|
+
if (error.name !== 'TimeoutError')
|
|
283
|
+
throw error;
|
|
284
|
+
});
|
|
272
285
|
const urls = await extractUrlsFromPage(playwrightContext.page, selector, options.baseUrl ?? playwrightContext.request.loadedUrl);
|
|
273
286
|
return (await this.#enqueueLinks(urls, options, playwrightContext.request));
|
|
274
287
|
},
|
|
@@ -277,39 +290,68 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
|
|
|
277
290
|
/**
|
|
278
291
|
* Runs one request handler attempt inside its own {@link StorageTransaction}, wrapping the inner
|
|
279
292
|
* (static or browser) context pipeline. The transaction is pushed to `transactions` *at creation
|
|
280
|
-
* time, before the `try
|
|
281
|
-
*
|
|
293
|
+
* time, before the `try`*, as failed attempts are routine here. The caller owns the outcome and
|
|
294
|
+
* disposal, including closing or reverting the {@link ContextModifications}.
|
|
295
|
+
*
|
|
296
|
+
* `request` defaults to the context's; a detection rerun passes a copy so it sees the request as it
|
|
297
|
+
* was before the browser attempt.
|
|
282
298
|
*/
|
|
283
|
-
async #crawlOne(renderingType, context, useStateFunction, transactions) {
|
|
299
|
+
async #crawlOne(renderingType, context, useStateFunction, transactions, request = context.request) {
|
|
284
300
|
const transaction = createStorageTransaction({
|
|
285
301
|
policy: this.#attemptWritePolicy,
|
|
286
302
|
commitTimeoutMillis: this.internalTimeoutMillis,
|
|
287
303
|
});
|
|
288
304
|
transactions.push(transaction);
|
|
289
305
|
const logs = [];
|
|
290
|
-
const
|
|
306
|
+
const contextModifications = {
|
|
307
|
+
request: new MutationJournal(),
|
|
308
|
+
state: new MutationJournal(),
|
|
309
|
+
};
|
|
310
|
+
const subCrawlerContext = Object.defineProperties({}, Object.getOwnPropertyDescriptors(context));
|
|
291
311
|
const attemptBoundContextHelpers = {
|
|
292
|
-
|
|
312
|
+
request: contextModifications.request.track(request),
|
|
313
|
+
useState: async (defaultValue) => contextModifications.state.track(await useStateFunction(defaultValue)),
|
|
293
314
|
log: this.#createLogProxy(context.log, logs),
|
|
294
|
-
|
|
315
|
+
// The sub-crawler pipeline keeps this attempt's navigation deadline on `subCrawlerContext`, but the
|
|
316
|
+
// outer `extendTimeout` only pushes the deadline it finds on `context`, so push this one as well.
|
|
317
|
+
extendTimeout: (secs) => {
|
|
318
|
+
context.extendTimeout(secs);
|
|
319
|
+
if (subCrawlerContext[navigationDeadlineKey] !== undefined) {
|
|
320
|
+
subCrawlerContext[navigationDeadlineKey] += secs * 1000;
|
|
321
|
+
}
|
|
322
|
+
},
|
|
295
323
|
};
|
|
296
|
-
const subCrawlerContext = Object.defineProperties({}, Object.getOwnPropertyDescriptors(context));
|
|
297
324
|
// Mark attempt-bound helpers as non-configurable so they survive the sub-crawler context pipeline
|
|
298
325
|
// (which would otherwise override them with the sub-crawler's own versions, losing the binding).
|
|
299
326
|
for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(attemptBoundContextHelpers))) {
|
|
300
327
|
Object.defineProperty(subCrawlerContext, key, { ...descriptor, configurable: false });
|
|
301
328
|
}
|
|
329
|
+
// The timeout below does not stop the request handler, and the pipeline closes the page only after the handler
|
|
330
|
+
// settles. Racing the handler against this lets a timed-out attempt release its page right away.
|
|
331
|
+
const attemptFailed = new AbortController();
|
|
302
332
|
try {
|
|
303
333
|
// Any failure - middleware or handler - ends up in the `ok: false` branch below.
|
|
304
334
|
const rethrow = (error) => {
|
|
305
335
|
throw error;
|
|
306
336
|
};
|
|
337
|
+
const abandonableRequestHandler = async (crawlingContext) => {
|
|
338
|
+
// The attempt may have failed before the handler starts, and a late abort listener would never fire.
|
|
339
|
+
attemptFailed.signal.throwIfAborted();
|
|
340
|
+
return Promise.race([
|
|
341
|
+
this.requestHandler(crawlingContext),
|
|
342
|
+
new Promise((_resolve, reject) => {
|
|
343
|
+
attemptFailed.signal.addEventListener('abort', () => reject(attemptFailed.signal.reason), {
|
|
344
|
+
once: true,
|
|
345
|
+
});
|
|
346
|
+
}),
|
|
347
|
+
]);
|
|
348
|
+
};
|
|
307
349
|
const callAdaptiveRequestHandler = async () => {
|
|
308
350
|
if (renderingType === 'static') {
|
|
309
351
|
await this.#staticContextPipeline.call(subCrawlerContext, this.requestHandler.bind(this), rethrow);
|
|
310
352
|
}
|
|
311
353
|
else if (renderingType === 'clientOnly') {
|
|
312
|
-
await this.#browserContextPipeline.call(subCrawlerContext,
|
|
354
|
+
await this.#browserContextPipeline.call(subCrawlerContext, abandonableRequestHandler, rethrow);
|
|
313
355
|
}
|
|
314
356
|
};
|
|
315
357
|
// this crawler overrides `runRequestHandler` and times each rendering-type run itself, so it has
|
|
@@ -317,13 +359,11 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
|
|
|
317
359
|
const routeTimeoutSecs = this.requestHandler.getTimeoutSecs?.(context.request.label);
|
|
318
360
|
const timeoutMillis = routeTimeoutSecs === undefined ? this.#individualRequestHandlerTimeoutMillis : routeTimeoutSecs * 1000;
|
|
319
361
|
await addTimeoutToPromise(async () => transaction.run(callAdaptiveRequestHandler), timeoutMillis, 'Request handler timed out');
|
|
320
|
-
return {
|
|
362
|
+
return { ok: true, transaction, contextModifications, logs };
|
|
321
363
|
}
|
|
322
364
|
catch (error) {
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
finally {
|
|
326
|
-
await Promise.all(deferredCleanup.map((cleanup) => cleanup()));
|
|
365
|
+
attemptFailed.abort(error);
|
|
366
|
+
return { ok: false, error, transaction, contextModifications, logs };
|
|
327
367
|
}
|
|
328
368
|
}
|
|
329
369
|
async runRequestHandler(crawlingContext) {
|
|
@@ -337,14 +377,19 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
|
|
|
337
377
|
// `finally` below, not earlier: the comparators read the journals after `crawlOne` returns.
|
|
338
378
|
const transactions = [];
|
|
339
379
|
try {
|
|
380
|
+
// A result the `resultChecker` rejected is as good as a detection saying the page needs a browser - but
|
|
381
|
+
// only once the browser run has succeeded. A thrown error says nothing about rendering.
|
|
382
|
+
let httpResultRejected = false;
|
|
340
383
|
if (renderingTypePrediction.renderingType === 'static' && !shouldDetectRenderingType) {
|
|
341
384
|
crawlingContext.log.debug(`Running HTTP-only request handler for ${crawlingContext.request.url}`);
|
|
342
385
|
this.statistics.state.httpOnlyRequestHandlerRuns++;
|
|
343
386
|
const plainHTTPRun = await this.#crawlOne('static', crawlingContext, crawlingContext.useState, transactions);
|
|
344
|
-
if (plainHTTPRun.ok &&
|
|
387
|
+
if (plainHTTPRun.ok &&
|
|
388
|
+
this.#resultChecker(plainHTTPRun.transaction, { request: crawlingContext.request })) {
|
|
345
389
|
crawlingContext.log.debug(`HTTP-only request handler succeeded for ${crawlingContext.request.url}`);
|
|
346
|
-
plainHTTPRun.logs
|
|
347
|
-
|
|
390
|
+
plainHTTPRun.logs.forEach(([log, method, ...args]) => log[method](...args));
|
|
391
|
+
this.#keepContextModifications(plainHTTPRun.contextModifications);
|
|
392
|
+
await plainHTTPRun.transaction.commit();
|
|
348
393
|
return;
|
|
349
394
|
}
|
|
350
395
|
// Execution will "fall through" and try running the request handler in a browser
|
|
@@ -355,6 +400,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
|
|
|
355
400
|
: plainHTTPRun.error;
|
|
356
401
|
if (actualError instanceof ContextPipelineInterruptedError ||
|
|
357
402
|
(await this.#shouldPropagateError(actualError, crawlingContext))) {
|
|
403
|
+
this.#keepContextModifications(plainHTTPRun.contextModifications);
|
|
358
404
|
throw actualError;
|
|
359
405
|
}
|
|
360
406
|
crawlingContext.log.exception(actualError, `HTTP-only request handler failed for ${crawlingContext.request.url}`);
|
|
@@ -362,47 +408,50 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
|
|
|
362
408
|
else {
|
|
363
409
|
crawlingContext.log.warning(`HTTP-only request handler returned a suspicious result for ${crawlingContext.request.url}`);
|
|
364
410
|
this.statistics.state.renderingTypeMispredictions++;
|
|
411
|
+
httpResultRejected = true;
|
|
365
412
|
}
|
|
413
|
+
// The browser attempt starts from the request and state as they were before the rejected one.
|
|
414
|
+
this.#discardContextModifications(plainHTTPRun.contextModifications, crawlingContext);
|
|
366
415
|
}
|
|
367
416
|
crawlingContext.log.debug(`Running browser request handler for ${crawlingContext.request.url}`);
|
|
368
417
|
this.statistics.state.browserRequestHandlerRuns++;
|
|
369
|
-
|
|
370
|
-
// a rendering type detection if necessary. Without this measure, the HTTP request handler would run
|
|
371
|
-
// under different conditions, which could change its behavior. Changes done to the crawler state by
|
|
372
|
-
// the HTTP request handler will not be committed to the actual storage.
|
|
373
|
-
const stateTracker = {
|
|
374
|
-
stateCopy: null,
|
|
375
|
-
async getLiveState(defaultValue = {}) {
|
|
376
|
-
const state = await crawlingContext.useState(defaultValue);
|
|
377
|
-
if (this.stateCopy === null) {
|
|
378
|
-
this.stateCopy = JSON.parse(JSON.stringify(state));
|
|
379
|
-
}
|
|
380
|
-
return state;
|
|
381
|
-
},
|
|
382
|
-
async getStateCopy(defaultValue = {}) {
|
|
383
|
-
if (this.stateCopy === null) {
|
|
384
|
-
return defaultValue;
|
|
385
|
-
}
|
|
386
|
-
return this.stateCopy;
|
|
387
|
-
},
|
|
388
|
-
};
|
|
389
|
-
const browserRun = await this.#crawlOne('clientOnly', crawlingContext, stateTracker.getLiveState.bind(stateTracker), transactions);
|
|
418
|
+
const browserRun = await this.#crawlOne('clientOnly', crawlingContext, crawlingContext.useState, transactions);
|
|
390
419
|
if (!browserRun.ok) {
|
|
420
|
+
// A failed browser attempt is handed to the retry logic with its writes - `userData` stashed for the
|
|
421
|
+
// next attempt must survive.
|
|
422
|
+
this.#keepContextModifications(browserRun.contextModifications);
|
|
391
423
|
throw browserRun.error;
|
|
392
424
|
}
|
|
393
|
-
|
|
394
|
-
|
|
425
|
+
try {
|
|
426
|
+
browserRun.logs.forEach(([log, method, ...args]) => log[method](...args));
|
|
427
|
+
// The `afterStorageCommit` callbacks belong to this attempt, so the detection rerun undoes their
|
|
428
|
+
// writes too - the journals stay open until they have run.
|
|
429
|
+
await browserRun.transaction.commit();
|
|
430
|
+
}
|
|
431
|
+
finally {
|
|
432
|
+
this.#keepContextModifications(browserRun.contextModifications);
|
|
433
|
+
}
|
|
434
|
+
// Past the shutdown fence, `teardown()` has already drained - and possibly torn down the predictor.
|
|
435
|
+
if (httpResultRejected && !this.#shutDown) {
|
|
436
|
+
this.#storeRenderingType(crawlingContext.request, 'clientOnly');
|
|
437
|
+
}
|
|
395
438
|
if (shouldDetectRenderingType) {
|
|
396
439
|
const detectionPromise = (async () => {
|
|
397
440
|
crawlingContext.log.debug(`Detecting rendering type for ${crawlingContext.request.url}`);
|
|
398
441
|
// The detection attempt's transaction is never committed - its writes exist only for the
|
|
399
|
-
// result comparison.
|
|
400
|
-
|
|
442
|
+
// result comparison. It runs on copies of the request and the crawler state with the browser
|
|
443
|
+
// attempt's writes undone, so both attempts start from the same conditions, and the copies go
|
|
444
|
+
// away with it.
|
|
445
|
+
const { request: requestJournal, state: stateJournal } = browserRun.contextModifications;
|
|
446
|
+
let stateCopy;
|
|
447
|
+
const plainHTTPRun = await this.#crawlOne('static', crawlingContext, async (defaultValue) => (stateCopy ??= stateJournal.undoOnto(JSON.parse(JSON.stringify(await crawlingContext.useState(defaultValue))))), transactions, requestJournal.undoOnto(CrawlingRequest.fromSchema(JSON.parse(JSON.stringify(crawlingContext.request)))));
|
|
401
448
|
const detectionResult = (() => {
|
|
402
449
|
if (!plainHTTPRun.ok) {
|
|
403
450
|
return 'clientOnly';
|
|
404
451
|
}
|
|
405
|
-
const comparisonResult = this.#resultComparator(plainHTTPRun.
|
|
452
|
+
const comparisonResult = this.#resultComparator(plainHTTPRun.transaction, browserRun.transaction, {
|
|
453
|
+
request: crawlingContext.request,
|
|
454
|
+
});
|
|
406
455
|
if (comparisonResult === true || comparisonResult === 'equal') {
|
|
407
456
|
return 'static';
|
|
408
457
|
}
|
|
@@ -413,13 +462,7 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
|
|
|
413
462
|
})();
|
|
414
463
|
crawlingContext.log.debug(`Detected rendering type ${detectionResult} for ${crawlingContext.request.url}`);
|
|
415
464
|
if (detectionResult !== undefined) {
|
|
416
|
-
|
|
417
|
-
// batching its writes, and the drain below catches whatever is still pending.
|
|
418
|
-
const stored = this.#renderingTypePredictor.value.storeResult(crawlingContext.request, detectionResult);
|
|
419
|
-
if (stored !== undefined) {
|
|
420
|
-
// Nothing downstream awaits this, so a failed write would otherwise be silent.
|
|
421
|
-
void this.#trackDetection(Promise.resolve(stored).catch((error) => this.log.exception(error, `Failed to store the rendering type detection result for ${crawlingContext.request.url}`)));
|
|
422
|
-
}
|
|
465
|
+
this.#storeRenderingType(crawlingContext.request, detectionResult);
|
|
423
466
|
}
|
|
424
467
|
})();
|
|
425
468
|
await this.#trackDetection(detectionPromise);
|
|
@@ -433,6 +476,31 @@ export class AdaptivePlaywrightCrawler extends BasicCrawler {
|
|
|
433
476
|
}
|
|
434
477
|
}
|
|
435
478
|
}
|
|
479
|
+
#keepContextModifications(modifications) {
|
|
480
|
+
modifications.request.close();
|
|
481
|
+
modifications.state.close();
|
|
482
|
+
}
|
|
483
|
+
#discardContextModifications(modifications, { request, log }) {
|
|
484
|
+
// Nothing else writes to a request while its handler runs, so a conflict means a write that bypassed
|
|
485
|
+
// the context (e.g. through a stashed reference) - it stays, but it is not what the retry logic expects.
|
|
486
|
+
modifications.request.revert({
|
|
487
|
+
onConflict: (key) => log.warning(`Request ${request.url}: '${String(key)}' was modified outside the request handler`),
|
|
488
|
+
});
|
|
489
|
+
// The state is shared with concurrent handlers; a conflict is one of them having written the same
|
|
490
|
+
// property meanwhile. Their value wins, and this attempt's write stays with it.
|
|
491
|
+
modifications.state.revert({
|
|
492
|
+
onConflict: (key) => log.debug(`Crawler state '${String(key)}' was changed concurrently; keeping the newer value`),
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
#storeRenderingType(request, renderingType) {
|
|
496
|
+
// Deliberately not awaited: a predictor that persists asynchronously gets to keep batching its writes,
|
|
497
|
+
// and `drainRenderingDetections()` catches whatever is still pending.
|
|
498
|
+
const stored = this.#renderingTypePredictor.value.storeResult(request, renderingType);
|
|
499
|
+
if (stored !== undefined) {
|
|
500
|
+
// Nothing downstream awaits this, so a failed write would otherwise be silent.
|
|
501
|
+
void this.#trackDetection(Promise.resolve(stored).catch((error) => this.log.exception(error, `Failed to store the rendering type detection result for ${request.url}`)));
|
|
502
|
+
}
|
|
503
|
+
}
|
|
436
504
|
async #enqueueLinks(urls, options, request) {
|
|
437
505
|
const baseUrl = resolveBaseUrlForEnqueueLinksFiltering({
|
|
438
506
|
enqueueStrategy: options?.strategy,
|
|
@@ -1,8 +1,16 @@
|
|
|
1
|
-
import type { Configuration } from '@crawlee/browser';
|
|
2
|
-
import type { BrowserPool, BrowserPoolHooks, BrowserPoolOptions, PlaywrightPlugin
|
|
1
|
+
import type { Configuration, CrawlerRemoteBrowserOptions } from '@crawlee/browser';
|
|
2
|
+
import type { BrowserPool, BrowserPoolHooks, BrowserPoolOptions, PlaywrightPlugin } from '@crawlee/browser-pool';
|
|
3
3
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
4
4
|
import type { Page } from 'playwright';
|
|
5
5
|
import type { PlaywrightLaunchContext } from './playwright-launcher.js';
|
|
6
|
+
/** {@link BrowserCrawlerOptions.remoteBrowser|`remoteBrowser`} for Playwright, with the protocol to connect over. */
|
|
7
|
+
export interface PlaywrightRemoteBrowserOptions extends CrawlerRemoteBrowserOptions {
|
|
8
|
+
/**
|
|
9
|
+
* `'cdp'` uses `connectOverCDP()` (the default), `'playwright'` uses `connect()` (Playwright's own WebSocket
|
|
10
|
+
* protocol, for endpoints started with `launchServer()`).
|
|
11
|
+
*/
|
|
12
|
+
protocol?: 'cdp' | 'playwright';
|
|
13
|
+
}
|
|
6
14
|
/** A {@link BrowserPool} of Playwright browsers, as built by {@link playwrightBrowserPool}. */
|
|
7
15
|
export type PlaywrightBrowserPool = BrowserPool<{
|
|
8
16
|
browserPlugins: [PlaywrightPlugin];
|
|
@@ -17,8 +25,8 @@ export interface PlaywrightBrowserPoolOptions extends Omit<BrowserPoolOptions, '
|
|
|
17
25
|
headless?: boolean;
|
|
18
26
|
/** Configuration to read the browser defaults from. Defaults to the global configuration. */
|
|
19
27
|
configuration?: Configuration;
|
|
20
|
-
}
|
|
21
|
-
|
|
28
|
+
/** Connect to a remote browser service instead of launching locally; see {@link BrowserCrawlerOptions.remoteBrowser}. */
|
|
29
|
+
remoteBrowser?: PlaywrightRemoteBrowserOptions;
|
|
22
30
|
}
|
|
23
31
|
/**
|
|
24
32
|
* Builds a {@link BrowserPool} of Playwright browsers to pass to a {@link PlaywrightCrawler} as its
|
|
@@ -45,27 +53,3 @@ export interface RemotePlaywrightBrowserPoolOptions extends Pick<PlaywrightBrows
|
|
|
45
53
|
* @category Browser management
|
|
46
54
|
*/
|
|
47
55
|
export declare function playwrightBrowserPool(options?: PlaywrightBrowserPoolOptions): PlaywrightBrowserPool;
|
|
48
|
-
/**
|
|
49
|
-
* The {@link RemoteBrowserPool} counterpart of {@link playwrightBrowserPool}: connects to a remote browser
|
|
50
|
-
* service (Browserbase, Browserless, Steel, ...) with a Playwright plugin derived from `launchContext`.
|
|
51
|
-
*
|
|
52
|
-
* A {@link PlaywrightCrawler} accepts the same connection details directly via
|
|
53
|
-
* {@link BrowserCrawlerOptions.remoteBrowser|`remoteBrowser`}; reach for this factory when you also need to
|
|
54
|
-
* tune the wrapping pool, or to share one remote pool between crawlers.
|
|
55
|
-
*
|
|
56
|
-
* **Example usage:**
|
|
57
|
-
*
|
|
58
|
-
* ```javascript
|
|
59
|
-
* const crawler = new PlaywrightCrawler({
|
|
60
|
-
* browserPool: remotePlaywrightBrowserPool({
|
|
61
|
-
* endpoint: 'wss://production-sfo.browserless.io?token=xxx',
|
|
62
|
-
* maxOpenBrowsers: 2,
|
|
63
|
-
* browserPoolOptions: { useFingerprints: false },
|
|
64
|
-
* }),
|
|
65
|
-
* requestHandler: async ({ page }) => { ... },
|
|
66
|
-
* });
|
|
67
|
-
* ```
|
|
68
|
-
*
|
|
69
|
-
* @category Browser management
|
|
70
|
-
*/
|
|
71
|
-
export declare function remotePlaywrightBrowserPool(options: RemotePlaywrightBrowserPoolOptions): RemoteBrowserPool<Page>;
|
|
@@ -27,33 +27,6 @@ export function playwrightBrowserPool(options = {}) {
|
|
|
27
27
|
const { launchContext, headless, configuration, ...poolOptions } = options;
|
|
28
28
|
return playwrightLauncher(launchContext, headless, configuration).createBrowserPool(poolOptions);
|
|
29
29
|
}
|
|
30
|
-
/**
|
|
31
|
-
* The {@link RemoteBrowserPool} counterpart of {@link playwrightBrowserPool}: connects to a remote browser
|
|
32
|
-
* service (Browserbase, Browserless, Steel, ...) with a Playwright plugin derived from `launchContext`.
|
|
33
|
-
*
|
|
34
|
-
* A {@link PlaywrightCrawler} accepts the same connection details directly via
|
|
35
|
-
* {@link BrowserCrawlerOptions.remoteBrowser|`remoteBrowser`}; reach for this factory when you also need to
|
|
36
|
-
* tune the wrapping pool, or to share one remote pool between crawlers.
|
|
37
|
-
*
|
|
38
|
-
* **Example usage:**
|
|
39
|
-
*
|
|
40
|
-
* ```javascript
|
|
41
|
-
* const crawler = new PlaywrightCrawler({
|
|
42
|
-
* browserPool: remotePlaywrightBrowserPool({
|
|
43
|
-
* endpoint: 'wss://production-sfo.browserless.io?token=xxx',
|
|
44
|
-
* maxOpenBrowsers: 2,
|
|
45
|
-
* browserPoolOptions: { useFingerprints: false },
|
|
46
|
-
* }),
|
|
47
|
-
* requestHandler: async ({ page }) => { ... },
|
|
48
|
-
* });
|
|
49
|
-
* ```
|
|
50
|
-
*
|
|
51
|
-
* @category Browser management
|
|
52
|
-
*/
|
|
53
|
-
export function remotePlaywrightBrowserPool(options) {
|
|
54
|
-
const { launchContext, headless, configuration, ...remoteOptions } = options;
|
|
55
|
-
return playwrightLauncher(launchContext, headless, configuration).createRemoteBrowserPool(remoteOptions);
|
|
56
|
-
}
|
|
57
30
|
function playwrightLauncher(launchContext = {}, headless, configuration) {
|
|
58
31
|
return new PlaywrightLauncher(headless == null
|
|
59
32
|
? launchContext
|
|
@@ -4,6 +4,7 @@ import type { Dictionary } from '@crawlee/types';
|
|
|
4
4
|
// @ts-ignore optional peer dependency or compatibility with es2022
|
|
5
5
|
import type { Page, Response } from 'playwright';
|
|
6
6
|
import { z } from 'zod';
|
|
7
|
+
import { type PlaywrightRemoteBrowserOptions } from './playwright-browser-pool.js';
|
|
7
8
|
import type { PlaywrightLaunchContext } from './playwright-launcher.js';
|
|
8
9
|
import type { DirectNavigationOptions, HandleCloudflareChallengeOptions, PlaywrightContextUtils } from './utils/playwright-utils.js';
|
|
9
10
|
export type PlaywrightGotoOptions = NonNullable<Parameters<Page['goto']>[1]>;
|
|
@@ -20,6 +21,8 @@ export interface PlaywrightCrawlerOptions<ContextExtension = Dictionary<never>,
|
|
|
20
21
|
* Can be also set via {@link Configuration}.
|
|
21
22
|
*/
|
|
22
23
|
headless?: boolean;
|
|
24
|
+
/** See {@link BrowserCrawlerOptions.remoteBrowser}; Playwright additionally lets you pick the `protocol`. */
|
|
25
|
+
remoteBrowser?: PlaywrightRemoteBrowserOptions;
|
|
23
26
|
/**
|
|
24
27
|
* Async functions that are sequentially evaluated before the navigation. Good for setting additional cookies
|
|
25
28
|
* or browser properties before navigation. The function receives the `crawlingContext`; the options object
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { BrowserCrawler, RequestState, Router, serviceLocator } from '@crawlee/browser';
|
|
2
2
|
import { assertBrowserPoolNotConfigured, parseArgument, schemas } from '@crawlee/utils/internal';
|
|
3
3
|
import { z } from 'zod';
|
|
4
|
-
import { playwrightBrowserPool
|
|
4
|
+
import { playwrightBrowserPool } from './playwright-browser-pool.js';
|
|
5
5
|
import { blockRequests, compileScript, enqueueLinksByClickingElements, gotoExtended, handleCloudflareChallenge, infiniteScroll, injectFile, injectJQuery, parseWithCheerio, saveSnapshot, } from './utils/playwright-utils.js';
|
|
6
6
|
/**
|
|
7
7
|
* Provides a simple framework for parallel crawling of web pages
|
|
@@ -99,9 +99,7 @@ export class PlaywrightCrawler extends BrowserCrawler {
|
|
|
99
99
|
super({
|
|
100
100
|
...browserCrawlerOptions,
|
|
101
101
|
configuration,
|
|
102
|
-
browserPoolBuilder: (remoteBrowser) => remoteBrowser
|
|
103
|
-
? remotePlaywrightBrowserPool({ ...remoteBrowser, launchContext, headless, configuration })
|
|
104
|
-
: playwrightBrowserPool({ launchContext, headless, configuration }),
|
|
102
|
+
browserPoolBuilder: (remoteBrowser) => playwrightBrowserPool({ launchContext, headless, configuration, remoteBrowser }),
|
|
105
103
|
contextPipelineBuilder: () => this.#buildContextPipeline(),
|
|
106
104
|
});
|
|
107
105
|
}
|
|
@@ -116,6 +114,21 @@ export class PlaywrightCrawler extends BrowserCrawler {
|
|
|
116
114
|
const locator = context.page.locator(selector).first();
|
|
117
115
|
await locator.waitFor({ timeout: timeoutMs, state: 'attached' });
|
|
118
116
|
};
|
|
117
|
+
const parseWithCheerioFn = async (selector, timeoutMs = 5_000) => {
|
|
118
|
+
if (selector) {
|
|
119
|
+
await waitForSelector(selector, timeoutMs);
|
|
120
|
+
}
|
|
121
|
+
return parseWithCheerio(context.page, this.ignoreShadowRoots, this.ignoreIframes);
|
|
122
|
+
};
|
|
123
|
+
const querySelectorAll = async (selector, timeoutMs) => {
|
|
124
|
+
const matches = (await parseWithCheerioFn(selector, timeoutMs))(selector);
|
|
125
|
+
// The browser located it but the Cheerio snapshot does not have it - a Playwright-only selector,
|
|
126
|
+
// or an element under a shadow root/iframe the snapshot was told to ignore.
|
|
127
|
+
if (matches.length === 0) {
|
|
128
|
+
throw new Error(`Selector '${selector}' not found in the page snapshot.`);
|
|
129
|
+
}
|
|
130
|
+
return matches;
|
|
131
|
+
};
|
|
119
132
|
const downloads = [];
|
|
120
133
|
context.page.on('download', (download) => downloads.push(download));
|
|
121
134
|
return {
|
|
@@ -130,12 +143,9 @@ export class PlaywrightCrawler extends BrowserCrawler {
|
|
|
130
143
|
},
|
|
131
144
|
blockRequests: async (options) => blockRequests(context.page, options),
|
|
132
145
|
waitForSelector,
|
|
133
|
-
parseWithCheerio:
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
}
|
|
137
|
-
return parseWithCheerio(context.page, this.ignoreShadowRoots, this.ignoreIframes);
|
|
138
|
-
},
|
|
146
|
+
parseWithCheerio: parseWithCheerioFn,
|
|
147
|
+
querySelectorAll,
|
|
148
|
+
querySelectorOne: async (selector, timeoutMs) => (await querySelectorAll(selector, timeoutMs)).first(),
|
|
139
149
|
infiniteScroll: async (options) => infiniteScroll(context.page, options),
|
|
140
150
|
listDownloads: async () => downloads,
|
|
141
151
|
saveSnapshot: async (options) => saveSnapshot(context.page, {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { BrowserLauncher, Configuration } from '@crawlee/browser';
|
|
2
|
-
import { PlaywrightPlugin } from '@crawlee/browser-pool';
|
|
2
|
+
import { PlaywrightPlugin, RemotePlaywrightPlugin } from '@crawlee/browser-pool';
|
|
3
3
|
import { parseArgument, schemas } from '@crawlee/utils/internal';
|
|
4
4
|
import { z } from 'zod';
|
|
5
5
|
/**
|
|
@@ -35,6 +35,7 @@ export class PlaywrightLauncher extends BrowserLauncher {
|
|
|
35
35
|
}, configuration);
|
|
36
36
|
this.configuration = configuration;
|
|
37
37
|
this.Plugin = PlaywrightPlugin;
|
|
38
|
+
this.RemotePlugin = RemotePlaywrightPlugin;
|
|
38
39
|
}
|
|
39
40
|
}
|
|
40
41
|
/**
|
|
@@ -19,7 +19,8 @@
|
|
|
19
19
|
*/
|
|
20
20
|
import { Configuration, type Request } from '@crawlee/browser';
|
|
21
21
|
import type { BatchAddRequestsResult, Dictionary } from '@crawlee/types';
|
|
22
|
-
import type { CheerioAPI } from 'cheerio';
|
|
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
25
|
import type { Download, Page, Response } from 'playwright';
|
|
25
26
|
import type { EnqueueLinksByClickingElementsOptions } from '../enqueue-links/click-elements.js';
|
|
@@ -420,6 +421,15 @@ export interface PlaywrightContextUtils {
|
|
|
420
421
|
* ```
|
|
421
422
|
*/
|
|
422
423
|
waitForSelector(selector: string, timeoutMs?: number): Promise<void>;
|
|
424
|
+
/**
|
|
425
|
+
* Like {@link PlaywrightContextUtils.waitForSelector|`waitForSelector`}, but returns the matched elements
|
|
426
|
+
* as a Cheerio object. Throws when nothing matches.
|
|
427
|
+
*/
|
|
428
|
+
querySelectorAll(selector: string, timeoutMs?: number): Promise<Cheerio<AnyNode>>;
|
|
429
|
+
/**
|
|
430
|
+
* Like {@link PlaywrightContextUtils.querySelectorAll|`querySelectorAll`}, but returns only the first match.
|
|
431
|
+
*/
|
|
432
|
+
querySelectorOne(selector: string, timeoutMs?: number): Promise<Cheerio<AnyNode>>;
|
|
423
433
|
/**
|
|
424
434
|
* Returns Cheerio handle for `page.content()`, allowing to work with the data same way as with {@link CheerioCrawler}.
|
|
425
435
|
* When provided with the `selector` argument, it waits for it to be available first.
|
|
@@ -9,8 +9,6 @@ export interface RenderingTypePredictorOptions {
|
|
|
9
9
|
/**
|
|
10
10
|
* Minimal contract that any object passed to {@link AdaptivePlaywrightCrawler} as its
|
|
11
11
|
* `renderingTypePredictor` option must satisfy.
|
|
12
|
-
*
|
|
13
|
-
* @experimental
|
|
14
12
|
*/
|
|
15
13
|
export interface IRenderingTypePredictor {
|
|
16
14
|
/**
|
|
@@ -24,7 +22,8 @@ export interface IRenderingTypePredictor {
|
|
|
24
22
|
detectionProbabilityRecommendation: number;
|
|
25
23
|
}>;
|
|
26
24
|
/**
|
|
27
|
-
* Report a
|
|
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.
|
|
28
27
|
*
|
|
29
28
|
* The crawler does not await this per detection - it collects the returned promises and drains them in
|
|
30
29
|
* `teardown()`, so an implementation that persists results asynchronously can keep batching its writes
|
|
@@ -34,8 +33,6 @@ export interface IRenderingTypePredictor {
|
|
|
34
33
|
}
|
|
35
34
|
/**
|
|
36
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.
|
|
37
|
-
*
|
|
38
|
-
* @experimental
|
|
39
36
|
*/
|
|
40
37
|
export declare class RenderingTypePredictor implements IRenderingTypePredictor {
|
|
41
38
|
#private;
|
|
@@ -62,8 +62,6 @@ 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;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crawlee/playwright",
|
|
3
|
-
"version": "4.0.0-rc.
|
|
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
6
|
"node": ">=22.13.0"
|
|
@@ -49,20 +49,22 @@
|
|
|
49
49
|
"dependencies": {
|
|
50
50
|
"@apify/datastructures": "^3.0.1",
|
|
51
51
|
"@apify/timeout": "^1.0.1",
|
|
52
|
-
"@crawlee/basic": "4.0.0-rc.
|
|
53
|
-
"@crawlee/browser": "4.0.0-rc.
|
|
54
|
-
"@crawlee/browser-pool": "4.0.0-rc.
|
|
55
|
-
"@crawlee/cheerio": "4.0.0-rc.
|
|
56
|
-
"@crawlee/core": "4.0.0-rc.
|
|
57
|
-
"@crawlee/
|
|
58
|
-
"@crawlee/
|
|
59
|
-
"
|
|
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.
|
|
64
|
+
"ml-matrix": "^6.15.1",
|
|
63
65
|
"string-comparison": "^1.3.0",
|
|
64
|
-
"tslib": "^2.
|
|
65
|
-
"zod": "^4.
|
|
66
|
+
"tslib": "^2.9.1",
|
|
67
|
+
"zod": "^4.6.7"
|
|
66
68
|
},
|
|
67
69
|
"peerDependencies": {
|
|
68
70
|
"playwright": "*"
|
|
@@ -79,5 +81,5 @@
|
|
|
79
81
|
}
|
|
80
82
|
}
|
|
81
83
|
},
|
|
82
|
-
"gitHead": "
|
|
84
|
+
"gitHead": "a9b623229cd7d1bff5063fc82940efebaea47165"
|
|
83
85
|
}
|