@crawlee/browser 4.0.0-beta.11 → 4.0.0-beta.111

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.
@@ -1,8 +1,22 @@
1
- import { BasicCrawler, BLOCKED_STATUS_CODES as DEFAULT_BLOCKED_STATUS_CODES, Configuration, ContextPipeline, cookieStringToToughCookie, enqueueLinks, EVENT_SESSION_RETIRED, handleRequestTimeout, RequestState, resolveBaseUrlForEnqueueLinksFiltering, SessionError, tryAbsoluteURL, validators, } from '@crawlee/basic';
2
- import { BrowserPool } from '@crawlee/browser-pool';
3
- import { CLOUDFLARE_RETRY_CSS_SELECTORS, RETRY_CSS_SELECTORS, sleep } from '@crawlee/utils';
1
+ import { BasicCrawler, browserPoolCookieToToughCookie, ContextPipeline, cookieStringToToughCookie, enqueueLinks, NavigationSkippedError, OwnedOrInjected, remainingNavigationWindowMillis, RequestState, resolveBaseUrlForEnqueueLinksFiltering, SessionError, toughCookieToBrowserPoolCookie, tryAbsoluteURL, validators, } from '@crawlee/basic';
2
+ import { BrowserPool, RemoteBrowserPool } from '@crawlee/browser-pool';
3
+ import { CLOUDFLARE_RETRY_CSS_SELECTORS, RETRY_CSS_SELECTORS } from '@crawlee/utils/internal';
4
+ import { sleep } from '@crawlee/utils';
4
5
  import ow from 'ow';
5
- import { tryCancel } from '@apify/timeout';
6
+ import { addTimeoutToPromise, TimeoutError, tryCancel } from '@apify/timeout';
7
+ const COOKIES_BEFORE_HOOKS = Symbol('cookiesBeforeHooks');
8
+ const readContextField = (ctx, key) => ctx[key];
9
+ /**
10
+ * Whether an error thrown by `page.goto()` is a navigation timeout - either our own {@link TimeoutError}
11
+ * or the driver's, which Playwright/Puppeteer report with their own class and a `Timeout ... exceeded` message
12
+ * naming the raw millisecond value rather than the configured window.
13
+ */
14
+ function isNavigationTimeoutError(error) {
15
+ return (error instanceof TimeoutError ||
16
+ error?.name === 'TimeoutError' ||
17
+ error?.constructor?.name === 'TimeoutError' ||
18
+ /timeout.*exceeded/i.test(error?.message ?? ''));
19
+ }
6
20
  /**
7
21
  * Provides a simple framework for parallel crawling of web pages
8
22
  * using headless browsers with [Puppeteer](https://github.com/puppeteer/puppeteer)
@@ -15,51 +29,51 @@ import { tryCancel } from '@apify/timeout';
15
29
  * If the target website doesn't need JavaScript, we should consider using the {@link CheerioCrawler},
16
30
  * which downloads the pages using raw HTTP requests and is about 10x faster.
17
31
  *
18
- * The source URLs are represented by the {@link Request} objects that are fed from the {@link RequestList} or {@link RequestQueue} instances
19
- * provided by the {@link BrowserCrawlerOptions.requestList|`requestList`} or {@link BrowserCrawlerOptions.requestQueue|`requestQueue`}
20
- * constructor options, respectively. If neither `requestList` nor `requestQueue` options are provided,
32
+ * The source URLs are represented by the {@link Request} objects that are fed from the
33
+ * {@link IRequestManager|request manager} provided via the {@link BrowserCrawlerOptions.requestManager|`requestManager`}
34
+ * constructor option (a {@link RequestQueue} is itself a request manager). If no `requestManager` is provided,
21
35
  * the crawler will open the default request queue either when the {@link BrowserCrawler.addRequests|`crawler.addRequests()`} function is called,
22
36
  * or if `requests` parameter (representing the initial requests) of the {@link BrowserCrawler.run|`crawler.run()`} function is provided.
23
37
  *
24
- * If both {@link BrowserCrawlerOptions.requestList|`requestList`} and {@link BrowserCrawlerOptions.requestQueue|`requestQueue`} options are used,
25
- * the instance first processes URLs from the {@link RequestList} and automatically enqueues all of them
26
- * to the {@link RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.
38
+ * To read from a read-only source such as a {@link RequestList} while still being able to enqueue new requests,
39
+ * combine it with a queue into a {@link RequestManagerTandem} via {@link IRequestLoader.toTandem|`requestLoader.toTandem()`}
40
+ * and pass the result as `requestManager`.
41
+ *
42
+ * > The {@link BrowserCrawlerOptions.requestList|`requestList`} and {@link BrowserCrawlerOptions.requestQueue|`requestQueue`}
43
+ * > options are deprecated; they are still accepted and folded into a single `requestManager` for back-compat.
27
44
  *
28
45
  * The crawler finishes when there are no more {@link Request} objects to crawl.
29
46
  *
30
47
  * `BrowserCrawler` opens a new browser page (i.e. tab or window) for each {@link Request} object to crawl
31
48
  * and then calls the function provided by user as the {@link BrowserCrawlerOptions.requestHandler|`requestHandler`} option.
32
49
  *
33
- * New pages are only opened when there is enough free CPU and memory available,
34
- * using the functionality provided by the {@link AutoscaledPool} class.
35
- * All {@link AutoscaledPool} configuration options can be passed to the {@link BrowserCrawlerOptions.autoscaledPoolOptions|`autoscaledPoolOptions`}
36
- * parameter of the `BrowserCrawler` constructor.
37
- * For user convenience, the {@link AutoscaledPoolOptions.minConcurrency|`minConcurrency`} and
38
- * {@link AutoscaledPoolOptions.maxConcurrency|`maxConcurrency`} options of the
39
- * underlying {@link AutoscaledPool} constructor are available directly in the `BrowserCrawler` constructor.
50
+ * New pages are only opened when there is enough free CPU and memory available, as judged by the crawler's
51
+ * {@link ConcurrencySystem}.
52
+ * Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the
53
+ * `BrowserCrawler` constructor, or, for finer control, by injecting a pre-configured
54
+ * {@link ConcurrencySystem|`concurrencySystem`}.
40
55
  *
41
56
  * > *NOTE:* the pool of browser instances is internally managed by the {@link BrowserPool} class.
42
57
  *
43
58
  * @category Crawlers
44
59
  */
45
60
  export class BrowserCrawler extends BasicCrawler {
46
- config;
47
- /**
48
- * A reference to the underlying {@link ProxyConfiguration} class that manages the crawler's proxies.
49
- * Only available if used by the crawler.
50
- */
51
- proxyConfiguration;
61
+ /** Backs the {@link BrowserCrawler.browserPool|`browserPool`} getter. */
62
+ #browserPoolDep;
52
63
  /**
53
- * A reference to the underlying {@link BrowserPool} class that manages the crawler's browsers.
64
+ * A reference to the underlying browser pool that manages the crawler's browsers. Typed as
65
+ * {@link IBrowserPool} so custom implementations can be plugged in via the `browserPool` constructor option.
54
66
  */
55
- browserPool;
67
+ get browserPool() {
68
+ return this.#browserPoolDep.value;
69
+ }
56
70
  launchContext;
57
71
  ignoreShadowRoots;
58
72
  ignoreIframes;
59
- navigationTimeoutMillis;
60
- preNavigationHooks;
61
- postNavigationHooks;
62
- persistCookiesPerSession;
73
+ #navigationTimeoutMillis;
74
+ #preNavigationHooks;
75
+ #postNavigationHooks;
76
+ #saveResponseCookies;
63
77
  static optionsShape = {
64
78
  ...BasicCrawler.optionsShape,
65
79
  navigationTimeoutSecs: ow.optional.number.greaterThan(0),
@@ -67,68 +81,107 @@ export class BrowserCrawler extends BasicCrawler {
67
81
  postNavigationHooks: ow.optional.array,
68
82
  launchContext: ow.optional.object,
69
83
  headless: ow.optional.any(ow.boolean, ow.string),
70
- browserPoolOptions: ow.object,
71
- sessionPoolOptions: ow.optional.object,
72
- persistCookiesPerSession: ow.optional.boolean,
73
- useSessionPool: ow.optional.boolean,
84
+ browserPool: ow.optional.object.validate(validators.browserPool),
85
+ remoteBrowser: ow.optional.object,
86
+ browserPoolOptions: ow.optional.object,
87
+ saveResponseCookies: ow.optional.boolean,
74
88
  proxyConfiguration: ow.optional.object.validate(validators.proxyConfiguration),
75
89
  };
76
90
  /**
77
91
  * All `BrowserCrawler` parameters are passed via an options object.
78
92
  */
79
- constructor(options, config = Configuration.getGlobalConfig()) {
93
+ constructor(options) {
80
94
  ow(options, 'BrowserCrawlerOptions', ow.object.exactShape(BrowserCrawler.optionsShape));
81
- const { navigationTimeoutSecs = 60, persistCookiesPerSession, proxyConfiguration, launchContext = {}, browserPoolOptions, preNavigationHooks = [], postNavigationHooks = [], headless, ignoreIframes = false, ignoreShadowRoots = false, contextPipelineBuilder, extendContext, ...basicCrawlerOptions } = options;
95
+ const { navigationTimeoutSecs = 60, saveResponseCookies = true, launchContext = {}, browserPool, remoteBrowser, browserPoolOptions, preNavigationHooks = [], postNavigationHooks = [], headless, ignoreIframes = false, ignoreShadowRoots = false, contextPipelineBuilder, extendContext, ...basicCrawlerOptions } = options;
96
+ const skipGuard = (action) => ({
97
+ action: async (ctx) => (ctx.request.skipNavigation ? {} : ((await action(ctx)) ?? {})),
98
+ });
82
99
  super({
83
100
  ...basicCrawlerOptions,
84
- contextPipelineBuilder: () => contextPipelineBuilder()
85
- .compose({ action: this.performNavigation.bind(this) })
86
- .compose({ action: this.handleBlockedRequestByContent.bind(this) })
87
- .compose({ action: this.restoreRequestState.bind(this) }),
88
- extendContext: extendContext,
89
- }, config);
90
- this.config = config;
91
- // Cookies should be persisted per session only if session pool is used
92
- if (!this.useSessionPool && persistCookiesPerSession) {
93
- throw new Error('You cannot use "persistCookiesPerSession" without "useSessionPool" set to true.');
94
- }
101
+ contextPipelineBuilder: () => {
102
+ // A single navigation window covers the pre-navigation hooks, the navigation, and the
103
+ // post-navigation hooks: the whole phase shares one `navigationTimeoutSecs` budget, so a slow
104
+ // hook eats into the same window the navigation uses. The navigation itself is bounded by
105
+ // capping its `gotoOptions.timeout` to the remaining budget.
106
+ const windowGuard = (step) => skipGuard(async (ctx) => {
107
+ const remaining = remainingNavigationWindowMillis(ctx, this.#navigationTimeoutMillis);
108
+ if (remaining <= 0) {
109
+ throw new TimeoutError(`Navigation timed out after ${this.#navigationTimeoutMillis / 1000} seconds.`);
110
+ }
111
+ return addTimeoutToPromise(async () => step(ctx), remaining, `Navigation timed out after ${this.#navigationTimeoutMillis / 1000} seconds.`);
112
+ });
113
+ let pipeline = contextPipelineBuilder().compose({ action: this.prepareNavigation.bind(this) });
114
+ for (const hook of this.#preNavigationHooks) {
115
+ pipeline = pipeline.compose(windowGuard(hook));
116
+ }
117
+ pipeline = pipeline.compose(skipGuard(this.navigate.bind(this)));
118
+ for (const hook of this.#postNavigationHooks) {
119
+ pipeline = pipeline.compose(windowGuard(hook));
120
+ }
121
+ return pipeline
122
+ .compose(skipGuard(this.finalizeNavigation.bind(this)))
123
+ .compose({ action: this.handleBlockedRequestByContent.bind(this) })
124
+ .compose({ action: this.restoreRequestState.bind(this) });
125
+ },
126
+ extendContext,
127
+ });
95
128
  this.launchContext = launchContext;
96
- this.navigationTimeoutMillis = navigationTimeoutSecs * 1000;
97
- this.proxyConfiguration = proxyConfiguration;
98
- this.preNavigationHooks = preNavigationHooks;
99
- this.postNavigationHooks = postNavigationHooks;
129
+ this.#navigationTimeoutMillis = navigationTimeoutSecs * 1000;
130
+ // The public option hooks are extension-aware; internal storage uses the base context type
131
+ // (the pipeline composes hooks against the concrete context, which does not statically carry
132
+ // `ContextExtension`). The extension members are present at runtime regardless.
133
+ this.#preNavigationHooks = preNavigationHooks;
134
+ this.#postNavigationHooks = postNavigationHooks;
100
135
  this.ignoreIframes = ignoreIframes;
101
136
  this.ignoreShadowRoots = ignoreShadowRoots;
102
137
  if (headless != null) {
103
138
  this.launchContext.launchOptions ??= {};
104
139
  this.launchContext.launchOptions.headless = headless;
105
140
  }
106
- if (this.useSessionPool) {
107
- this.persistCookiesPerSession = persistCookiesPerSession !== undefined ? persistCookiesPerSession : true;
108
- }
109
- else {
110
- this.persistCookiesPerSession = false;
111
- }
112
- if (launchContext?.userAgent) {
113
- if (browserPoolOptions.useFingerprints)
114
- this.log.info('Custom user agent provided, disabling automatic browser fingerprint injection!');
115
- browserPoolOptions.useFingerprints = false;
116
- }
117
- const { preLaunchHooks = [], postLaunchHooks = [], ...rest } = browserPoolOptions;
118
- this.browserPool = new BrowserPool({
119
- ...rest,
120
- preLaunchHooks: [this._extendLaunchContext.bind(this), ...preLaunchHooks],
121
- postLaunchHooks: [this._maybeAddSessionRetiredListener.bind(this), ...postLaunchHooks],
141
+ this.#saveResponseCookies = saveResponseCookies;
142
+ // `browserPool` wins over `remoteBrowser` a passed-in pool is used as-is (borrowed), the sugar is ignored.
143
+ // The default is only built when no pool was injected, so all the option/launchContext fiddling below stays
144
+ // inside the factory.
145
+ this.#browserPoolDep = OwnedOrInjected.resolve(browserPool, () => {
146
+ const resolvedBrowserPoolOptions = browserPoolOptions ?? {};
147
+ if (launchContext?.userAgent) {
148
+ if (resolvedBrowserPoolOptions.useFingerprints)
149
+ this.log.info('Custom user agent provided, disabling automatic browser fingerprint injection!');
150
+ resolvedBrowserPoolOptions.useFingerprints = false;
151
+ }
152
+ if (remoteBrowser) {
153
+ // The crawler already built the right plugin for its browser — hand it to a RemoteBrowserPool so the
154
+ // remote connection is always for the matching browser (no plugin to construct, no way to mismatch).
155
+ const { browserPlugins, ...remoteBrowserPoolOptions } = resolvedBrowserPoolOptions;
156
+ return new RemoteBrowserPool({
157
+ browserPlugins: browserPlugins,
158
+ ...remoteBrowser,
159
+ browserPoolOptions: remoteBrowserPoolOptions,
160
+ });
161
+ }
162
+ // Double cast: `BrowserPool` implements `IBrowserPool<PageReturn>`, where `PageReturn` is derived from the
163
+ // plugin/controller generics and doesn't overlap with the crawler's free `Page` type param, so TS won't
164
+ // narrow it directly. The concrete pool does satisfy the `Page`/`destroy` contract at runtime — this is the
165
+ // long-standing `Page` variance gap, not a `destroy`-related hole.
166
+ return new BrowserPool({
167
+ ...resolvedBrowserPoolOptions,
168
+ });
122
169
  });
123
170
  }
171
+ getNavigationTimeoutMillis() {
172
+ return this.#navigationTimeoutMillis;
173
+ }
124
174
  buildContextPipeline() {
125
175
  return ContextPipeline.create().compose({
126
176
  action: this.preparePage.bind(this),
127
177
  cleanup: async (context) => {
128
178
  context.registerDeferredCleanup(async () => {
129
- await context.page
130
- .close()
131
- .catch((error) => this.log.debug('Error while closing page', { error }));
179
+ const error = !context.session.isUsable()
180
+ ? new SessionError('Session is no longer usable')
181
+ : undefined;
182
+ await this.browserPool
183
+ .closePage(context.page, { error })
184
+ .catch((closeError) => this.log.debug('Error while closing page', { error: closeError }));
132
185
  });
133
186
  },
134
187
  });
@@ -142,12 +195,6 @@ export class BrowserCrawler extends BasicCrawler {
142
195
  }
143
196
  async isRequestBlocked(crawlingContext) {
144
197
  const { page, response } = crawlingContext;
145
- const blockedStatusCodes =
146
- // eslint-disable-next-line dot-notation
147
- (this.sessionPool?.['blockedStatusCodes'].length ?? 0) > 0
148
- ? // eslint-disable-next-line dot-notation
149
- this.sessionPool['blockedStatusCodes']
150
- : DEFAULT_BLOCKED_STATUS_CODES;
151
198
  // Cloudflare specific heuristic - wait 5 seconds if we get a 403 for the JS challenge to load / resolve.
152
199
  if ((await this.containsSelectors(page, CLOUDFLARE_RETRY_CSS_SELECTORS)) && response?.status() === 403) {
153
200
  await sleep(5000);
@@ -158,117 +205,158 @@ export class BrowserCrawler extends BasicCrawler {
158
205
  return `Cloudflare challenge failed, found selectors: ${foundSelectors.join(', ')}`;
159
206
  }
160
207
  const foundSelectors = await this.containsSelectors(page, RETRY_CSS_SELECTORS);
161
- const blockedStatusCode = blockedStatusCodes.find((x) => x === (response?.status() ?? 0));
208
+ const statusCode = response?.status() ?? 0;
162
209
  if (foundSelectors)
163
210
  return `Found selectors: ${foundSelectors.join(', ')}`;
164
- if (blockedStatusCode)
165
- return `Received blocked status code: ${blockedStatusCode}`;
211
+ if (this.blockedStatusCodes.has(statusCode))
212
+ return `Received blocked status code: ${statusCode}`;
166
213
  return false;
167
214
  }
168
215
  async preparePage(crawlingContext) {
169
- const newPageOptions = {
216
+ const page = await this.browserPool.newPage({
170
217
  id: crawlingContext.id,
171
- };
172
- const useIncognitoPages = this.launchContext?.useIncognitoPages;
173
- if (this.proxyConfiguration) {
174
- const { session } = crawlingContext;
175
- const proxyInfo = await this.proxyConfiguration.newProxyInfo(session?.id, {
176
- request: crawlingContext.request,
177
- });
178
- crawlingContext.proxyInfo = proxyInfo;
179
- newPageOptions.proxyUrl = proxyInfo?.url;
180
- newPageOptions.proxyTier = proxyInfo?.proxyTier;
181
- if (this.proxyConfiguration.isManInTheMiddle) {
182
- /**
183
- * @see https://playwright.dev/docs/api/class-browser/#browser-new-context
184
- * @see https://github.com/puppeteer/puppeteer/blob/main/docs/api.md
185
- */
186
- newPageOptions.pageOptions = {
187
- ignoreHTTPSErrors: true,
188
- acceptInsecureCerts: true,
189
- };
190
- }
191
- }
192
- const page = (await this.browserPool.newPage(newPageOptions));
218
+ session: crawlingContext.session,
219
+ });
193
220
  tryCancel();
194
- const browserControllerInstance = this.browserPool.getBrowserControllerByPage(page);
221
+ const contextEnqueueLinks = crawlingContext.enqueueLinks;
195
222
  return {
196
223
  page,
197
224
  get response() {
198
225
  throw new Error("The `response` property is not available. This might mean that you're trying to access it before navigation or that navigation resulted in `null` (this should only happen with `about:` URLs)");
199
226
  },
200
- browserController: browserControllerInstance,
201
- session: useIncognitoPages
202
- ? crawlingContext.session
203
- : browserControllerInstance.launchContext.session,
204
- proxyInfo: crawlingContext.proxyInfo ?? browserControllerInstance.launchContext.proxyInfo,
227
+ get gotoOptions() {
228
+ throw new Error('The `gotoOptions` property is not available until `prepareNavigation` runs.');
229
+ },
205
230
  enqueueLinks: async (enqueueOptions = {}) => {
206
- return browserCrawlerEnqueueLinks({
207
- options: enqueueOptions,
231
+ return (await browserCrawlerEnqueueLinks({
232
+ options: {
233
+ ...enqueueOptions,
234
+ limit: await this.calculateEnqueuedRequestLimit(enqueueOptions?.limit),
235
+ },
208
236
  page,
209
- requestQueue: await this.getRequestQueue(),
237
+ requestManager: await this.getRequestManager(),
210
238
  robotsTxtFile: await this.getRobotsTxtFileForUrl(crawlingContext.request.url),
211
- onSkippedRequest: this.onSkippedRequest,
239
+ onSkippedRequest: this.handleSkippedRequest,
212
240
  originalRequestUrl: crawlingContext.request.url,
213
241
  finalRequestUrl: crawlingContext.request.loadedUrl,
214
- });
242
+ enqueueLinks: contextEnqueueLinks,
243
+ })); // TODO make this type safe
215
244
  },
216
245
  };
217
246
  }
218
- async performNavigation(crawlingContext) {
247
+ async prepareNavigation(crawlingContext) {
219
248
  if (crawlingContext.request.skipNavigation) {
220
249
  return {
221
250
  request: new Proxy(crawlingContext.request, {
222
251
  get(target, propertyName, receiver) {
223
252
  if (propertyName === 'loadedUrl') {
224
- throw new Error('The `request.loadedUrl` property is not available - `skipNavigation` was used');
253
+ throw new NavigationSkippedError('The `request.loadedUrl` property is not available - `skipNavigation` was used');
225
254
  }
226
255
  return Reflect.get(target, propertyName, receiver);
227
256
  },
228
257
  }),
229
258
  get response() {
230
- throw new Error('The `response` property is not available - `skipNavigation` was used');
259
+ throw new NavigationSkippedError('The `response` property is not available - `skipNavigation` was used');
231
260
  },
232
261
  };
233
262
  }
234
- const gotoOptions = { timeout: this.navigationTimeoutMillis };
235
- const preNavigationHooksCookies = this._getCookieHeaderFromRequest(crawlingContext.request);
236
263
  crawlingContext.request.state = RequestState.BEFORE_NAV;
237
- await this._executeHooks(this.preNavigationHooks, crawlingContext, gotoOptions);
264
+ return {
265
+ // Default to the full navigation timeout so a pre-navigation hook can read it; `navigate` narrows it
266
+ // to the remaining shared window unless a hook overrode it (see there).
267
+ gotoOptions: { timeout: this.#navigationTimeoutMillis },
268
+ [COOKIES_BEFORE_HOOKS]: this.getCookieHeaderFromRequest(crawlingContext.request),
269
+ };
270
+ }
271
+ async navigate(crawlingContext) {
238
272
  tryCancel();
239
- const postNavigationHooksCookies = this._getCookieHeaderFromRequest(crawlingContext.request);
240
- await this._applyCookies(crawlingContext, preNavigationHooksCookies, postNavigationHooksCookies);
273
+ const gotoOptions = crawlingContext.gotoOptions;
274
+ const remaining = remainingNavigationWindowMillis(crawlingContext, this.#navigationTimeoutMillis);
275
+ if (remaining <= 0) {
276
+ throw new TimeoutError(`Navigation timed out after ${this.#navigationTimeoutMillis / 1000} seconds.`);
277
+ }
278
+ // If a hook left the default `navigationTimeoutMillis` in place, bound the goto to whatever is left of the
279
+ // shared navigation window. If it overrode the value - including `0`, Playwright's "no timeout" - honour
280
+ // that verbatim as the goto's own timeout. The driver enforces this natively (so a timed-out goto is
281
+ // aborted, not left lingering) and `handleNavigationTimeout` turns its error into our own message.
282
+ const gotoTimeout = gotoOptions;
283
+ if (gotoTimeout.timeout === this.#navigationTimeoutMillis) {
284
+ gotoTimeout.timeout = remaining;
285
+ }
286
+ const cookiesBeforeHooks = readContextField(crawlingContext, COOKIES_BEFORE_HOOKS);
287
+ const cookiesAfterHooks = this.getCookieHeaderFromRequest(crawlingContext.request);
288
+ await this.applyCookies(crawlingContext, cookiesBeforeHooks, cookiesAfterHooks);
241
289
  let response;
242
290
  try {
243
- response = (await this._navigationHandler(crawlingContext, gotoOptions)) ?? undefined;
291
+ response = (await this.navigationHandler(crawlingContext, gotoOptions)) ?? undefined;
244
292
  }
245
293
  catch (error) {
246
- await this._handleNavigationTimeout(crawlingContext, error);
294
+ await this.handleNavigationTimeout(crawlingContext, error);
247
295
  crawlingContext.request.state = RequestState.ERROR;
248
- this._throwIfProxyError(error);
296
+ this.throwIfProxyError(error);
249
297
  throw error;
250
298
  }
251
299
  tryCancel();
252
300
  crawlingContext.request.state = RequestState.AFTER_NAV;
253
- await this._executeHooks(this.postNavigationHooks, crawlingContext, gotoOptions);
301
+ return { response };
302
+ }
303
+ async finalizeNavigation(crawlingContext) {
304
+ tryCancel();
305
+ let response;
306
+ try {
307
+ response = crawlingContext.response;
308
+ }
309
+ catch {
310
+ // `preparePage` installs a throwing getter for `response`; reaching this branch means
311
+ // navigation produced no response and no hook overrode it. Treat as undefined.
312
+ }
254
313
  await this.processResponse(response, crawlingContext);
255
314
  tryCancel();
256
- // save cookies
257
- // TODO: Should we save the cookies also after/only the handle page?
258
- if (this.persistCookiesPerSession) {
259
- const cookies = await crawlingContext.browserController.getCookies(crawlingContext.page);
260
- tryCancel();
261
- crawlingContext.session?.setCookies(cookies, crawlingContext.request.loadedUrl);
315
+ // Persist cookies from the navigation response before the user handler runs.
316
+ // Cookies set during `requestHandler` are saved again afterwards.
317
+ await this.persistCookiesFromPage(crawlingContext);
318
+ return { request: crawlingContext.request };
319
+ }
320
+ /**
321
+ * Copies cookies from the live browser page into the session cookie jar.
322
+ */
323
+ async persistCookiesFromPage(crawlingContext) {
324
+ if (!this.#saveResponseCookies || !crawlingContext.session) {
325
+ return;
262
326
  }
263
- if (response !== undefined) {
264
- return {
265
- request: crawlingContext.request,
266
- response,
267
- };
327
+ const { cookies } = await this.browserPool.extractPageState(crawlingContext.page);
328
+ tryCancel();
329
+ // Prefer the live page URL — the handler may have navigated after the initial load.
330
+ const url = (await crawlingContext.page.url()) || crawlingContext.request.loadedUrl || crawlingContext.request.url;
331
+ for (const cookie of cookies) {
332
+ try {
333
+ await crawlingContext.session.cookieJar.setCookie(browserPoolCookieToToughCookie(cookie), url, {
334
+ ignoreError: false,
335
+ });
336
+ }
337
+ catch (e) {
338
+ this.log.debug(`Could not set cookie: ${e.message}`);
339
+ }
340
+ }
341
+ }
342
+ /**
343
+ * Runs the user request handler, then re-reads browser cookies so login flows /
344
+ * `page.setCookie` / XHR `Set-Cookie` updates are stored for later requests.
345
+ */
346
+ async runRequestHandler(crawlingContext) {
347
+ try {
348
+ await super.runRequestHandler(crawlingContext);
349
+ }
350
+ finally {
351
+ if (!crawlingContext.request.skipNavigation) {
352
+ try {
353
+ await this.persistCookiesFromPage(crawlingContext);
354
+ }
355
+ catch {
356
+ // Page may already be closed on some failure paths; ignore.
357
+ }
358
+ }
268
359
  }
269
- return {
270
- request: crawlingContext.request,
271
- };
272
360
  }
273
361
  async handleBlockedRequestByContent(crawlingContext) {
274
362
  if (this.retryOnBlocked) {
@@ -282,30 +370,38 @@ export class BrowserCrawler extends BasicCrawler {
282
370
  crawlingContext.request.state = RequestState.REQUEST_HANDLER;
283
371
  return {};
284
372
  }
285
- async _applyCookies({ session, request, page, browserController }, preHooksCookies, postHooksCookies) {
286
- const sessionCookie = session?.getCookies(request.url) ?? [];
373
+ async applyCookies({ session, request, page }, preHooksCookies, postHooksCookies) {
374
+ const sessionCookie = session
375
+ ? (await session.cookieJar.getCookies(request.url)).map(toughCookieToBrowserPoolCookie)
376
+ : [];
287
377
  const parsedPreHooksCookies = preHooksCookies.split(/ *; */).map((c) => cookieStringToToughCookie(c));
288
378
  const parsedPostHooksCookies = postHooksCookies.split(/ *; */).map((c) => cookieStringToToughCookie(c));
289
- await browserController.setCookies(page, [...sessionCookie, ...parsedPreHooksCookies, ...parsedPostHooksCookies]
379
+ const cookies = [...sessionCookie, ...parsedPreHooksCookies, ...parsedPostHooksCookies]
290
380
  .filter((c) => typeof c !== 'undefined' && c !== null)
291
- .map((c) => ({ ...c, url: c.domain ? undefined : request.url })));
381
+ .map((c) => ({ ...c, url: c.domain ? undefined : request.url }));
382
+ await this.browserPool.injectPageState(page, { cookies });
292
383
  }
293
384
  /**
294
- * Marks session bad in case of navigation timeout.
385
+ * Marks session bad on navigation timeout, and stops in-flight page loading on any navigation error.
295
386
  */
296
- async _handleNavigationTimeout(crawlingContext, error) {
297
- const { session } = crawlingContext;
298
- if (error && error.constructor.name === 'TimeoutError') {
299
- handleRequestTimeout({ session, errorMessage: error.message });
387
+ async handleNavigationTimeout(crawlingContext, error) {
388
+ const { session, page } = crawlingContext;
389
+ // Fire-and-forget: no user code will run on this page after a failed navigation.
390
+ // Swallow rejections: the page may already be detached.
391
+ void page.evaluate(() => window.stop()).catch(() => { });
392
+ if (isNavigationTimeoutError(error)) {
393
+ session?.markBad();
394
+ // The driver was handed the remaining window (usually shorter than `navigationTimeoutSecs` once the
395
+ // hooks have run), so it names that value in its own error; report the configured window instead.
396
+ throw new TimeoutError(`Navigation timed out after ${this.#navigationTimeoutMillis / 1000} seconds.`);
300
397
  }
301
- await crawlingContext.page.close();
302
398
  }
303
399
  /**
304
400
  * Transforms proxy-related errors to `SessionError`.
305
401
  */
306
- _throwIfProxyError(error) {
402
+ throwIfProxyError(error) {
307
403
  if (this.isProxyError(error)) {
308
- throw new SessionError(this._getMessageFromError(error));
404
+ throw new SessionError(this.getMessageFromError(error));
309
405
  }
310
406
  }
311
407
  async processResponse(response, crawlingContext) {
@@ -313,10 +409,16 @@ export class BrowserCrawler extends BasicCrawler {
313
409
  if (typeof response === 'object' && typeof response.status === 'function') {
314
410
  const status = response.status();
315
411
  this.stats.registerStatusCode(status);
412
+ if (this.isErrorStatusCode(status)) {
413
+ if (this.additionalHttpErrorStatusCodes.has(status)) {
414
+ throw new Error(`${status} - Error status code was set by user.`);
415
+ }
416
+ throw new Error(`${status} - Internal Server Error`);
417
+ }
316
418
  }
317
419
  if (this.sessionPool && response && session) {
318
420
  if (typeof response === 'object' && typeof response.status === 'function') {
319
- this._throwOnBlockedRequest(session, response.status());
421
+ this.throwOnBlockedRequest(response.status());
320
422
  }
321
423
  else {
322
424
  this.log.debug('Got a malformed Browser response.', { request, response });
@@ -324,68 +426,43 @@ export class BrowserCrawler extends BasicCrawler {
324
426
  }
325
427
  request.loadedUrl = await page.url();
326
428
  }
327
- async _extendLaunchContext(_pageId, launchContext) {
328
- const launchContextExtends = {};
329
- if (this.sessionPool) {
330
- launchContextExtends.session = await this.sessionPool.getSession();
331
- }
332
- if (this.proxyConfiguration && !launchContext.proxyUrl) {
333
- const proxyInfo = await this.proxyConfiguration.newProxyInfo(launchContextExtends.session?.id, {
334
- proxyTier: launchContext.proxyTier ?? undefined,
335
- });
336
- launchContext.proxyUrl = proxyInfo?.url;
337
- launchContextExtends.proxyInfo = proxyInfo;
338
- // Disable SSL verification for MITM proxies
339
- if (this.proxyConfiguration.isManInTheMiddle) {
340
- /**
341
- * @see https://playwright.dev/docs/api/class-browser/#browser-new-context
342
- * @see https://github.com/puppeteer/puppeteer/blob/main/docs/api.md
343
- */
344
- launchContext.launchOptions.ignoreHTTPSErrors = true;
345
- launchContext.launchOptions.acceptInsecureCerts = true;
346
- }
347
- }
348
- launchContext.extend(launchContextExtends);
349
- }
350
- _maybeAddSessionRetiredListener(_pageId, browserController) {
351
- if (this.sessionPool) {
352
- const listener = (session) => {
353
- const { launchContext } = browserController;
354
- if (session.id === launchContext.session.id) {
355
- this.browserPool.retireBrowserController(browserController);
356
- }
357
- };
358
- this.sessionPool.on(EVENT_SESSION_RETIRED, listener);
359
- browserController.on("browserClosed" /* BROWSER_CONTROLLER_EVENTS.BROWSER_CLOSED */, () => {
360
- return this.sessionPool.removeListener(EVENT_SESSION_RETIRED, listener);
361
- });
362
- }
363
- }
364
429
  /**
365
430
  * Function for cleaning up after all requests are processed.
366
431
  * @ignore
367
432
  */
368
433
  async teardown() {
369
- await this.browserPool.destroy();
434
+ await this.#browserPoolDep.ifOwned((pool) => pool.destroy());
370
435
  await super.teardown();
371
436
  }
372
437
  }
373
438
  /** @internal */
374
- export async function browserCrawlerEnqueueLinks({ options, page, requestQueue, robotsTxtFile, onSkippedRequest, originalRequestUrl, finalRequestUrl, }) {
439
+ function containsEnqueueLinks(options) {
440
+ return !!options.enqueueLinks;
441
+ }
442
+ /** @internal */
443
+ export async function browserCrawlerEnqueueLinks(options) {
444
+ const { options: enqueueLinksOptions, finalRequestUrl, originalRequestUrl, page } = options;
375
445
  const baseUrl = resolveBaseUrlForEnqueueLinksFiltering({
376
- enqueueStrategy: options?.strategy,
446
+ enqueueStrategy: enqueueLinksOptions?.strategy,
377
447
  finalRequestUrl,
378
448
  originalRequestUrl,
379
- userProvidedBaseUrl: options?.baseUrl,
449
+ userProvidedBaseUrl: enqueueLinksOptions?.baseUrl,
380
450
  });
381
- const urls = await extractUrlsFromPage(page, options?.selector ?? 'a', options?.baseUrl ?? finalRequestUrl ?? originalRequestUrl);
451
+ const urls = await extractUrlsFromPage(page, enqueueLinksOptions?.selector ?? 'a', enqueueLinksOptions?.baseUrl ?? finalRequestUrl ?? originalRequestUrl);
452
+ if (containsEnqueueLinks(options)) {
453
+ return options.enqueueLinks({
454
+ urls,
455
+ baseUrl,
456
+ ...enqueueLinksOptions,
457
+ });
458
+ }
382
459
  return enqueueLinks({
383
- requestQueue,
384
- robotsTxtFile,
385
- onSkippedRequest,
460
+ requestManager: options.requestManager,
461
+ robotsTxtFile: options.robotsTxtFile,
462
+ onSkippedRequest: options.onSkippedRequest,
386
463
  urls,
387
464
  baseUrl,
388
- ...options,
465
+ ...enqueueLinksOptions,
389
466
  });
390
467
  }
391
468
  /**
@@ -413,4 +490,3 @@ page, selector, baseUrl) {
413
490
  })
414
491
  .filter((href) => !!href);
415
492
  }
416
- //# sourceMappingURL=browser-crawler.js.map