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