@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.
- 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 +274 -198
- 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,22 @@
|
|
|
1
|
-
import { BasicCrawler,
|
|
2
|
-
import { BrowserPool } from '@crawlee/browser-pool';
|
|
3
|
-
import { CLOUDFLARE_RETRY_CSS_SELECTORS, RETRY_CSS_SELECTORS
|
|
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
|
|
19
|
-
*
|
|
20
|
-
* constructor
|
|
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
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
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
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
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
|
|
93
|
+
constructor(options) {
|
|
80
94
|
ow(options, 'BrowserCrawlerOptions', ow.object.exactShape(BrowserCrawler.optionsShape));
|
|
81
|
-
const { navigationTimeoutSecs = 60,
|
|
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: () =>
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
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
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
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
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
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
|
-
|
|
130
|
-
|
|
131
|
-
|
|
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
|
|
208
|
+
const statusCode = response?.status() ?? 0;
|
|
162
209
|
if (foundSelectors)
|
|
163
210
|
return `Found selectors: ${foundSelectors.join(', ')}`;
|
|
164
|
-
if (
|
|
165
|
-
return `Received blocked status code: ${
|
|
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
|
|
216
|
+
const page = await this.browserPool.newPage({
|
|
170
217
|
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));
|
|
218
|
+
session: crawlingContext.session,
|
|
219
|
+
});
|
|
193
220
|
tryCancel();
|
|
194
|
-
const
|
|
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
|
-
|
|
201
|
-
|
|
202
|
-
|
|
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:
|
|
231
|
+
return (await browserCrawlerEnqueueLinks({
|
|
232
|
+
options: {
|
|
233
|
+
...enqueueOptions,
|
|
234
|
+
limit: await this.calculateEnqueuedRequestLimit(enqueueOptions?.limit),
|
|
235
|
+
},
|
|
208
236
|
page,
|
|
209
|
-
|
|
237
|
+
requestManager: await this.getRequestManager(),
|
|
210
238
|
robotsTxtFile: await this.getRobotsTxtFileForUrl(crawlingContext.request.url),
|
|
211
|
-
onSkippedRequest: this.
|
|
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
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
|
240
|
-
|
|
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.
|
|
291
|
+
response = (await this.navigationHandler(crawlingContext, gotoOptions)) ?? undefined;
|
|
244
292
|
}
|
|
245
293
|
catch (error) {
|
|
246
|
-
await this.
|
|
294
|
+
await this.handleNavigationTimeout(crawlingContext, error);
|
|
247
295
|
crawlingContext.request.state = RequestState.ERROR;
|
|
248
|
-
this.
|
|
296
|
+
this.throwIfProxyError(error);
|
|
249
297
|
throw error;
|
|
250
298
|
}
|
|
251
299
|
tryCancel();
|
|
252
300
|
crawlingContext.request.state = RequestState.AFTER_NAV;
|
|
253
|
-
|
|
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
|
-
//
|
|
257
|
-
//
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
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
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
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
|
|
286
|
-
const sessionCookie = session
|
|
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
|
-
|
|
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
|
|
385
|
+
* Marks session bad on navigation timeout, and stops in-flight page loading on any navigation error.
|
|
295
386
|
*/
|
|
296
|
-
async
|
|
297
|
-
const { session } = crawlingContext;
|
|
298
|
-
|
|
299
|
-
|
|
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
|
-
|
|
402
|
+
throwIfProxyError(error) {
|
|
307
403
|
if (this.isProxyError(error)) {
|
|
308
|
-
throw new SessionError(this.
|
|
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.
|
|
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.
|
|
434
|
+
await this.#browserPoolDep.ifOwned((pool) => pool.destroy());
|
|
370
435
|
await super.teardown();
|
|
371
436
|
}
|
|
372
437
|
}
|
|
373
438
|
/** @internal */
|
|
374
|
-
|
|
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:
|
|
446
|
+
enqueueStrategy: enqueueLinksOptions?.strategy,
|
|
377
447
|
finalRequestUrl,
|
|
378
448
|
originalRequestUrl,
|
|
379
|
-
userProvidedBaseUrl:
|
|
449
|
+
userProvidedBaseUrl: enqueueLinksOptions?.baseUrl,
|
|
380
450
|
});
|
|
381
|
-
const urls = await extractUrlsFromPage(page,
|
|
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
|
-
|
|
384
|
-
robotsTxtFile,
|
|
385
|
-
onSkippedRequest,
|
|
460
|
+
requestManager: options.requestManager,
|
|
461
|
+
robotsTxtFile: options.robotsTxtFile,
|
|
462
|
+
onSkippedRequest: options.onSkippedRequest,
|
|
386
463
|
urls,
|
|
387
464
|
baseUrl,
|
|
388
|
-
...
|
|
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
|