@crawlee/cheerio 3.0.3-beta.8 → 3.0.4-beta.0
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 +1 -1
- package/index.d.ts +1 -1
- package/index.d.ts.map +1 -1
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/index.mjs +3 -0
- package/internals/cheerio-crawler.d.ts +39 -350
- package/internals/cheerio-crawler.d.ts.map +1 -1
- package/internals/cheerio-crawler.js +45 -529
- package/internals/cheerio-crawler.js.map +1 -1
- package/package.json +4 -9
- package/tsconfig.build.tsbuildinfo +1 -1
|
@@ -2,34 +2,10 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.createCheerioRouter = exports.cheerioCrawlerEnqueueLinks = exports.CheerioCrawler = void 0;
|
|
4
4
|
const tslib_1 = require("tslib");
|
|
5
|
-
const
|
|
6
|
-
const utilities_1 = require("@apify/utilities");
|
|
7
|
-
const basic_1 = require("@crawlee/basic");
|
|
8
|
-
const core_1 = require("@crawlee/core");
|
|
9
|
-
const utils_1 = require("@crawlee/utils");
|
|
5
|
+
const http_1 = require("@crawlee/http");
|
|
10
6
|
const cheerio = tslib_1.__importStar(require("cheerio"));
|
|
11
|
-
const content_type_1 = tslib_1.__importDefault(require("content-type"));
|
|
12
|
-
const got_scraping_1 = require("got-scraping");
|
|
13
7
|
const htmlparser2_1 = require("htmlparser2");
|
|
14
8
|
const WritableStream_1 = require("htmlparser2/lib/WritableStream");
|
|
15
|
-
const iconv_lite_1 = tslib_1.__importDefault(require("iconv-lite"));
|
|
16
|
-
const ow_1 = tslib_1.__importDefault(require("ow"));
|
|
17
|
-
const util_1 = tslib_1.__importDefault(require("util"));
|
|
18
|
-
/**
|
|
19
|
-
* Default mime types, which CheerioScraper supports.
|
|
20
|
-
*/
|
|
21
|
-
const HTML_AND_XML_MIME_TYPES = ['text/html', 'text/xml', 'application/xhtml+xml', 'application/xml'];
|
|
22
|
-
const APPLICATION_JSON_MIME_TYPE = 'application/json';
|
|
23
|
-
const CHEERIO_OPTIMIZED_AUTOSCALED_POOL_OPTIONS = {
|
|
24
|
-
desiredConcurrency: 10,
|
|
25
|
-
snapshotterOptions: {
|
|
26
|
-
eventLoopSnapshotIntervalSecs: 2,
|
|
27
|
-
maxBlockedMillis: 100,
|
|
28
|
-
},
|
|
29
|
-
systemStatusOptions: {
|
|
30
|
-
maxEventLoopOverloadedRatio: 0.7,
|
|
31
|
-
},
|
|
32
|
-
};
|
|
33
9
|
/**
|
|
34
10
|
* Provides a framework for the parallel crawling of web pages using plain HTTP requests and
|
|
35
11
|
* [cheerio](https://www.npmjs.com/package/cheerio) HTML parser.
|
|
@@ -38,23 +14,23 @@ const CHEERIO_OPTIMIZED_AUTOSCALED_POOL_OPTIONS = {
|
|
|
38
14
|
*
|
|
39
15
|
* Since `CheerioCrawler` uses raw HTTP requests to download web pages,
|
|
40
16
|
* it is very fast and efficient on data bandwidth. However, if the target website requires JavaScript
|
|
41
|
-
* to display the content, you might need to use {@
|
|
17
|
+
* to display the content, you might need to use {@apilink PuppeteerCrawler} or {@apilink PlaywrightCrawler} instead,
|
|
42
18
|
* because it loads the pages using full-featured headless Chrome browser.
|
|
43
19
|
*
|
|
44
20
|
* `CheerioCrawler` downloads each URL using a plain HTTP request,
|
|
45
21
|
* parses the HTML content using [Cheerio](https://www.npmjs.com/package/cheerio)
|
|
46
|
-
* and then invokes the user-provided {@
|
|
22
|
+
* and then invokes the user-provided {@apilink CheerioCrawlerOptions.requestHandler} to extract page data
|
|
47
23
|
* using a [jQuery](https://jquery.com/)-like interface to the parsed HTML DOM.
|
|
48
24
|
*
|
|
49
|
-
* The source URLs are represented using {@
|
|
50
|
-
* {@
|
|
51
|
-
* or {@
|
|
25
|
+
* The source URLs are represented using {@apilink Request} objects that are fed from
|
|
26
|
+
* {@apilink RequestList} or {@apilink RequestQueue} instances provided by the {@apilink CheerioCrawlerOptions.requestList}
|
|
27
|
+
* or {@apilink CheerioCrawlerOptions.requestQueue} constructor options, respectively.
|
|
52
28
|
*
|
|
53
|
-
* If both {@
|
|
54
|
-
* the instance first processes URLs from the {@
|
|
55
|
-
* to {@
|
|
29
|
+
* If both {@apilink CheerioCrawlerOptions.requestList} and {@apilink CheerioCrawlerOptions.requestQueue} are used,
|
|
30
|
+
* the instance first processes URLs from the {@apilink RequestList} and automatically enqueues all of them
|
|
31
|
+
* to {@apilink RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.
|
|
56
32
|
*
|
|
57
|
-
* The crawler finishes when there are no more {@
|
|
33
|
+
* The crawler finishes when there are no more {@apilink Request} objects to crawl.
|
|
58
34
|
*
|
|
59
35
|
* We can use the `preNavigationHooks` to adjust `gotOptions`:
|
|
60
36
|
*
|
|
@@ -69,28 +45,20 @@ const CHEERIO_OPTIMIZED_AUTOSCALED_POOL_OPTIONS = {
|
|
|
69
45
|
* By default, `CheerioCrawler` only processes web pages with the `text/html`
|
|
70
46
|
* and `application/xhtml+xml` MIME content types (as reported by the `Content-Type` HTTP header),
|
|
71
47
|
* and skips pages with other content types. If you want the crawler to process other content types,
|
|
72
|
-
* use the {@
|
|
48
|
+
* use the {@apilink CheerioCrawlerOptions.additionalMimeTypes} constructor option.
|
|
73
49
|
* Beware that the parsing behavior differs for HTML, XML, JSON and other types of content.
|
|
74
|
-
* For details, see {@
|
|
50
|
+
* For more details, see {@apilink CheerioCrawlerOptions.requestHandler}.
|
|
75
51
|
*
|
|
76
52
|
* New requests are only dispatched when there is enough free CPU and memory available,
|
|
77
|
-
* using the functionality provided by the {@
|
|
78
|
-
* All {@
|
|
53
|
+
* using the functionality provided by the {@apilink AutoscaledPool} class.
|
|
54
|
+
* All {@apilink AutoscaledPool} configuration options can be passed to the `autoscaledPoolOptions`
|
|
79
55
|
* parameter of the `CheerioCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency`
|
|
80
|
-
* {@
|
|
56
|
+
* {@apilink AutoscaledPool} options are available directly in the `CheerioCrawler` constructor.
|
|
81
57
|
*
|
|
82
58
|
* **Example usage:**
|
|
83
59
|
*
|
|
84
60
|
* ```javascript
|
|
85
|
-
* // Prepare a list of URLs to crawl
|
|
86
|
-
* const requestList = await RequestList.open(null, [
|
|
87
|
-
* { url: 'http://www.example.com/page-1' },
|
|
88
|
-
* { url: 'http://www.example.com/page-2' },
|
|
89
|
-
* ]);
|
|
90
|
-
*
|
|
91
|
-
* // Crawl the URLs
|
|
92
61
|
* const crawler = new CheerioCrawler({
|
|
93
|
-
* requestList,
|
|
94
62
|
* async requestHandler({ request, response, body, contentType, $ }) {
|
|
95
63
|
* const data = [];
|
|
96
64
|
*
|
|
@@ -108,213 +76,37 @@ const CHEERIO_OPTIMIZED_AUTOSCALED_POOL_OPTIONS = {
|
|
|
108
76
|
* },
|
|
109
77
|
* });
|
|
110
78
|
*
|
|
111
|
-
* await crawler.run(
|
|
79
|
+
* await crawler.run([
|
|
80
|
+
* 'http://www.example.com/page-1',
|
|
81
|
+
* 'http://www.example.com/page-2',
|
|
82
|
+
* ]);
|
|
112
83
|
* ```
|
|
113
84
|
* @category Crawlers
|
|
114
85
|
*/
|
|
115
|
-
class CheerioCrawler extends
|
|
86
|
+
class CheerioCrawler extends http_1.HttpCrawler {
|
|
116
87
|
/**
|
|
117
88
|
* All `CheerioCrawler` parameters are passed via an options object.
|
|
118
89
|
*/
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
// but not too much so that we would stall the crawler.
|
|
132
|
-
requestHandlerTimeoutSecs: navigationTimeoutSecs + requestHandlerTimeoutSecs + basic_1.BASIC_CRAWLER_TIMEOUT_BUFFER_SECS,
|
|
133
|
-
}, config);
|
|
134
|
-
Object.defineProperty(this, "config", {
|
|
135
|
-
enumerable: true,
|
|
136
|
-
configurable: true,
|
|
137
|
-
writable: true,
|
|
138
|
-
value: config
|
|
139
|
-
});
|
|
140
|
-
/**
|
|
141
|
-
* A reference to the underlying {@link ProxyConfiguration} class that manages the crawler's proxies.
|
|
142
|
-
* Only available if used by the crawler.
|
|
143
|
-
*/
|
|
144
|
-
Object.defineProperty(this, "proxyConfiguration", {
|
|
145
|
-
enumerable: true,
|
|
146
|
-
configurable: true,
|
|
147
|
-
writable: true,
|
|
148
|
-
value: void 0
|
|
149
|
-
});
|
|
150
|
-
Object.defineProperty(this, "userRequestHandlerTimeoutMillis", {
|
|
151
|
-
enumerable: true,
|
|
152
|
-
configurable: true,
|
|
153
|
-
writable: true,
|
|
154
|
-
value: void 0
|
|
155
|
-
});
|
|
156
|
-
Object.defineProperty(this, "preNavigationHooks", {
|
|
157
|
-
enumerable: true,
|
|
158
|
-
configurable: true,
|
|
159
|
-
writable: true,
|
|
160
|
-
value: void 0
|
|
161
|
-
});
|
|
162
|
-
Object.defineProperty(this, "postNavigationHooks", {
|
|
163
|
-
enumerable: true,
|
|
164
|
-
configurable: true,
|
|
165
|
-
writable: true,
|
|
166
|
-
value: void 0
|
|
167
|
-
});
|
|
168
|
-
Object.defineProperty(this, "persistCookiesPerSession", {
|
|
169
|
-
enumerable: true,
|
|
170
|
-
configurable: true,
|
|
171
|
-
writable: true,
|
|
172
|
-
value: void 0
|
|
173
|
-
});
|
|
174
|
-
Object.defineProperty(this, "navigationTimeoutMillis", {
|
|
175
|
-
enumerable: true,
|
|
176
|
-
configurable: true,
|
|
177
|
-
writable: true,
|
|
178
|
-
value: void 0
|
|
90
|
+
// eslint-disable-next-line @typescript-eslint/no-useless-constructor
|
|
91
|
+
constructor(options, config) {
|
|
92
|
+
super(options, config);
|
|
93
|
+
}
|
|
94
|
+
async _parseHTML(response, isXml, crawlingContext) {
|
|
95
|
+
const dom = await this._parseHtmlToDom(response);
|
|
96
|
+
const $ = cheerio.load(dom, {
|
|
97
|
+
xmlMode: isXml,
|
|
98
|
+
// Recent versions of cheerio use parse5 as the HTML parser/serializer. It's more strict than htmlparser2
|
|
99
|
+
// and not good for scraping. It also does not have a great streaming interface.
|
|
100
|
+
// Here we tell cheerio to use htmlparser2 for serialization, otherwise the conflict produces weird errors.
|
|
101
|
+
_useHtmlParser2: true,
|
|
179
102
|
});
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
enumerable: true,
|
|
188
|
-
configurable: true,
|
|
189
|
-
writable: true,
|
|
190
|
-
value: void 0
|
|
191
|
-
});
|
|
192
|
-
Object.defineProperty(this, "forceResponseEncoding", {
|
|
193
|
-
enumerable: true,
|
|
194
|
-
configurable: true,
|
|
195
|
-
writable: true,
|
|
196
|
-
value: void 0
|
|
197
|
-
});
|
|
198
|
-
Object.defineProperty(this, "supportedMimeTypes", {
|
|
199
|
-
enumerable: true,
|
|
200
|
-
configurable: true,
|
|
201
|
-
writable: true,
|
|
202
|
-
value: void 0
|
|
203
|
-
});
|
|
204
|
-
/**
|
|
205
|
-
* @internal wraps public utility for mocking purposes
|
|
206
|
-
*/
|
|
207
|
-
Object.defineProperty(this, "_requestAsBrowser", {
|
|
208
|
-
enumerable: true,
|
|
209
|
-
configurable: true,
|
|
210
|
-
writable: true,
|
|
211
|
-
value: (options) => {
|
|
212
|
-
return new Promise((resolve, reject) => {
|
|
213
|
-
const stream = (0, got_scraping_1.gotScraping)(options);
|
|
214
|
-
stream.on('error', reject);
|
|
215
|
-
stream.on('response', () => {
|
|
216
|
-
resolve(addResponsePropertiesToStream(stream));
|
|
217
|
-
});
|
|
218
|
-
});
|
|
219
|
-
}
|
|
220
|
-
});
|
|
221
|
-
this._handlePropertyNameChange({
|
|
222
|
-
newName: 'requestHandler',
|
|
223
|
-
oldName: 'handlePageFunction',
|
|
224
|
-
propertyKey: 'requestHandler',
|
|
225
|
-
newProperty: requestHandler,
|
|
226
|
-
oldProperty: handlePageFunction,
|
|
227
|
-
allowUndefined: true,
|
|
228
|
-
});
|
|
229
|
-
if (!this.requestHandler) {
|
|
230
|
-
this.requestHandler = this.router;
|
|
231
|
-
}
|
|
232
|
-
// Cookies should be persisted per session only if session pool is used
|
|
233
|
-
if (!this.useSessionPool && persistCookiesPerSession) {
|
|
234
|
-
throw new Error('You cannot use "persistCookiesPerSession" without "useSessionPool" set to true.');
|
|
235
|
-
}
|
|
236
|
-
this.supportedMimeTypes = new Set([...HTML_AND_XML_MIME_TYPES, APPLICATION_JSON_MIME_TYPE]);
|
|
237
|
-
if (additionalMimeTypes.length)
|
|
238
|
-
this._extendSupportedMimeTypes(additionalMimeTypes);
|
|
239
|
-
if (suggestResponseEncoding && forceResponseEncoding) {
|
|
240
|
-
this.log.warning('Both forceResponseEncoding and suggestResponseEncoding options are set. Using forceResponseEncoding.');
|
|
241
|
-
}
|
|
242
|
-
this.userRequestHandlerTimeoutMillis = requestHandlerTimeoutSecs * 1000;
|
|
243
|
-
this.navigationTimeoutMillis = navigationTimeoutSecs * 1000;
|
|
244
|
-
this.ignoreSslErrors = ignoreSslErrors;
|
|
245
|
-
this.suggestResponseEncoding = suggestResponseEncoding;
|
|
246
|
-
this.forceResponseEncoding = forceResponseEncoding;
|
|
247
|
-
this.proxyConfiguration = proxyConfiguration;
|
|
248
|
-
this.preNavigationHooks = preNavigationHooks;
|
|
249
|
-
this.postNavigationHooks = [
|
|
250
|
-
({ request, response }) => this._abortDownloadOfBody(request, response),
|
|
251
|
-
...postNavigationHooks,
|
|
252
|
-
];
|
|
253
|
-
if (this.useSessionPool) {
|
|
254
|
-
this.persistCookiesPerSession = persistCookiesPerSession ?? true;
|
|
255
|
-
}
|
|
256
|
-
else {
|
|
257
|
-
this.persistCookiesPerSession = false;
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
/**
|
|
261
|
-
* **EXPERIMENTAL**
|
|
262
|
-
* Function for attaching CrawlerExtensions such as the Unblockers.
|
|
263
|
-
* @param extension Crawler extension that overrides the crawler configuration.
|
|
264
|
-
*/
|
|
265
|
-
use(extension) {
|
|
266
|
-
(0, ow_1.default)(extension, ow_1.default.object.instanceOf(core_1.CrawlerExtension));
|
|
267
|
-
const extensionOptions = extension.getCrawlerOptions();
|
|
268
|
-
for (const [key, value] of (0, utils_1.entries)(extensionOptions)) {
|
|
269
|
-
const isConfigurable = this.hasOwnProperty(key);
|
|
270
|
-
const originalType = typeof this[key];
|
|
271
|
-
const extensionType = typeof value; // What if we want to null something? It is really needed?
|
|
272
|
-
const isSameType = originalType === extensionType || value == null; // fast track for deleting keys
|
|
273
|
-
const exists = this[key] != null;
|
|
274
|
-
if (!isConfigurable) { // Test if the property can be configured on the crawler
|
|
275
|
-
throw new Error(`${extension.name} tries to set property "${key}" that is not configurable on CheerioCrawler instance.`);
|
|
276
|
-
}
|
|
277
|
-
if (!isSameType && exists) { // Assuming that extensions will only add up configuration
|
|
278
|
-
throw new Error(`${extension.name} tries to set property of different type "${extensionType}". "CheerioCrawler.${key}: ${originalType}".`);
|
|
279
|
-
}
|
|
280
|
-
this.log.warning(`${extension.name} is overriding "CheerioCrawler.${key}: ${originalType}" with ${value}.`);
|
|
281
|
-
this[key] = value;
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
/**
|
|
285
|
-
* Wrapper around requestHandler that opens and closes pages etc.
|
|
286
|
-
*/
|
|
287
|
-
async _runRequestHandler(crawlingContext) {
|
|
288
|
-
const { request, session } = crawlingContext;
|
|
289
|
-
if (this.proxyConfiguration) {
|
|
290
|
-
const sessionId = session ? session.id : undefined;
|
|
291
|
-
crawlingContext.proxyInfo = await this.proxyConfiguration.newProxyInfo(sessionId);
|
|
292
|
-
}
|
|
293
|
-
if (!request.skipNavigation) {
|
|
294
|
-
await this._handleNavigation(crawlingContext);
|
|
295
|
-
(0, timeout_1.tryCancel)();
|
|
296
|
-
const { dom, isXml, body, contentType, response } = await this._parseResponse(request, crawlingContext.response);
|
|
297
|
-
(0, timeout_1.tryCancel)();
|
|
298
|
-
if (this.useSessionPool) {
|
|
299
|
-
this._throwOnBlockedRequest(session, response.statusCode);
|
|
300
|
-
}
|
|
301
|
-
if (this.persistCookiesPerSession) {
|
|
302
|
-
session.setCookiesFromResponse(response);
|
|
303
|
-
}
|
|
304
|
-
request.loadedUrl = response.url;
|
|
305
|
-
const $ = dom
|
|
306
|
-
? cheerio.load(dom, {
|
|
307
|
-
xmlMode: isXml,
|
|
308
|
-
// Recent versions of cheerio use parse5 as the HTML parser/serializer. It's more strict than htmlparser2
|
|
309
|
-
// and not good for scraping. It also does not have a great streaming interface.
|
|
310
|
-
// Here we tell cheerio to use htmlparser2 for serialization, otherwise the conflict produces weird errors.
|
|
311
|
-
_useHtmlParser2: true,
|
|
312
|
-
})
|
|
313
|
-
: null;
|
|
314
|
-
crawlingContext.$ = $;
|
|
315
|
-
crawlingContext.contentType = contentType;
|
|
316
|
-
crawlingContext.response = response;
|
|
317
|
-
crawlingContext.enqueueLinks = async (enqueueOptions) => {
|
|
103
|
+
return {
|
|
104
|
+
dom,
|
|
105
|
+
$,
|
|
106
|
+
get body() {
|
|
107
|
+
return isXml ? $.xml() : $.html({ decodeEntities: false });
|
|
108
|
+
},
|
|
109
|
+
enqueueLinks: async (enqueueOptions) => {
|
|
318
110
|
return cheerioCrawlerEnqueueLinks({
|
|
319
111
|
options: enqueueOptions,
|
|
320
112
|
$,
|
|
@@ -322,200 +114,8 @@ class CheerioCrawler extends basic_1.BasicCrawler {
|
|
|
322
114
|
originalRequestUrl: crawlingContext.request.url,
|
|
323
115
|
finalRequestUrl: crawlingContext.request.loadedUrl,
|
|
324
116
|
});
|
|
325
|
-
};
|
|
326
|
-
Object.defineProperty(crawlingContext, 'json', {
|
|
327
|
-
get() {
|
|
328
|
-
if (contentType.type !== APPLICATION_JSON_MIME_TYPE)
|
|
329
|
-
return null;
|
|
330
|
-
const jsonString = body.toString(contentType.encoding);
|
|
331
|
-
return JSON.parse(jsonString);
|
|
332
|
-
},
|
|
333
|
-
});
|
|
334
|
-
Object.defineProperty(crawlingContext, 'body', {
|
|
335
|
-
get() {
|
|
336
|
-
// NOTE: For XML/HTML documents, we don't store the original body and only reconstruct it from Cheerio's DOM.
|
|
337
|
-
// This is to save memory for high-concurrency crawls. The downside is that changes
|
|
338
|
-
// made to DOM are reflected in the HTML, but we can live with that...
|
|
339
|
-
if (dom) {
|
|
340
|
-
return isXml ? $.xml() : $.html({ decodeEntities: false });
|
|
341
|
-
}
|
|
342
|
-
return body;
|
|
343
|
-
},
|
|
344
|
-
});
|
|
345
|
-
}
|
|
346
|
-
return (0, timeout_1.addTimeoutToPromise)(() => Promise.resolve(this.requestHandler(crawlingContext)), this.userRequestHandlerTimeoutMillis, `requestHandler timed out after ${this.userRequestHandlerTimeoutMillis / 1000} seconds.`);
|
|
347
|
-
}
|
|
348
|
-
async _handleNavigation(crawlingContext) {
|
|
349
|
-
const gotOptions = {};
|
|
350
|
-
const { request, session } = crawlingContext;
|
|
351
|
-
const preNavigationHooksCookies = this._getCookieHeaderFromRequest(request);
|
|
352
|
-
// Execute pre navigation hooks before applying session pool cookies,
|
|
353
|
-
// as they may also set cookies in the session
|
|
354
|
-
await this._executeHooks(this.preNavigationHooks, crawlingContext, gotOptions);
|
|
355
|
-
(0, timeout_1.tryCancel)();
|
|
356
|
-
const postNavigationHooksCookies = this._getCookieHeaderFromRequest(request);
|
|
357
|
-
this._applyCookies(crawlingContext, gotOptions, preNavigationHooksCookies, postNavigationHooksCookies);
|
|
358
|
-
const proxyUrl = crawlingContext.proxyInfo?.url;
|
|
359
|
-
crawlingContext.response = await (0, timeout_1.addTimeoutToPromise)(() => this._requestFunction({ request, session, proxyUrl, gotOptions }), this.navigationTimeoutMillis, `request timed out after ${this.navigationTimeoutMillis / 1000} seconds.`);
|
|
360
|
-
(0, timeout_1.tryCancel)();
|
|
361
|
-
await this._executeHooks(this.postNavigationHooks, crawlingContext, gotOptions);
|
|
362
|
-
(0, timeout_1.tryCancel)();
|
|
363
|
-
}
|
|
364
|
-
/**
|
|
365
|
-
* Sets the cookie header to `gotOptions` based on the provided request and session headers, as well as any changes that occurred due to hooks.
|
|
366
|
-
*/
|
|
367
|
-
_applyCookies({ session, request }, gotOptions, preHookCookies, postHookCookies) {
|
|
368
|
-
const sessionCookie = session?.getCookieString(request.url) ?? '';
|
|
369
|
-
let alteredGotOptionsCookies = (gotOptions.headers?.Cookie || gotOptions.headers?.cookie || '');
|
|
370
|
-
if (gotOptions.headers?.Cookie && gotOptions.headers?.cookie) {
|
|
371
|
-
const { Cookie: upperCaseHeader, cookie: lowerCaseHeader, } = gotOptions.headers;
|
|
372
|
-
// eslint-disable-next-line max-len
|
|
373
|
-
this.log.warning(`Encountered mixed casing for the cookie headers in the got options for request ${request.url} (${request.id}). Their values will be merged`);
|
|
374
|
-
const sourceCookies = [];
|
|
375
|
-
if (Array.isArray(lowerCaseHeader)) {
|
|
376
|
-
sourceCookies.push(...lowerCaseHeader);
|
|
377
|
-
}
|
|
378
|
-
else {
|
|
379
|
-
sourceCookies.push(lowerCaseHeader);
|
|
380
|
-
}
|
|
381
|
-
if (Array.isArray(upperCaseHeader)) {
|
|
382
|
-
sourceCookies.push(...upperCaseHeader);
|
|
383
|
-
}
|
|
384
|
-
else {
|
|
385
|
-
sourceCookies.push(upperCaseHeader);
|
|
386
|
-
}
|
|
387
|
-
alteredGotOptionsCookies = (0, core_1.mergeCookies)(request.url, sourceCookies);
|
|
388
|
-
}
|
|
389
|
-
const sourceCookies = [
|
|
390
|
-
sessionCookie,
|
|
391
|
-
preHookCookies,
|
|
392
|
-
];
|
|
393
|
-
if (Array.isArray(alteredGotOptionsCookies)) {
|
|
394
|
-
sourceCookies.push(...alteredGotOptionsCookies);
|
|
395
|
-
}
|
|
396
|
-
else {
|
|
397
|
-
sourceCookies.push(alteredGotOptionsCookies);
|
|
398
|
-
}
|
|
399
|
-
sourceCookies.push(postHookCookies);
|
|
400
|
-
const mergedCookie = (0, core_1.mergeCookies)(request.url, sourceCookies);
|
|
401
|
-
gotOptions.headers ?? (gotOptions.headers = {});
|
|
402
|
-
Reflect.deleteProperty(gotOptions.headers, 'Cookie');
|
|
403
|
-
Reflect.deleteProperty(gotOptions.headers, 'cookie');
|
|
404
|
-
gotOptions.headers.Cookie = mergedCookie;
|
|
405
|
-
}
|
|
406
|
-
/**
|
|
407
|
-
* Function to make the HTTP request. It performs optimizations
|
|
408
|
-
* on the request such as only downloading the request body if the
|
|
409
|
-
* received content type matches text/html, application/xml, application/xhtml+xml.
|
|
410
|
-
*/
|
|
411
|
-
async _requestFunction({ request, session, proxyUrl, gotOptions }) {
|
|
412
|
-
const opts = this._getRequestOptions(request, session, proxyUrl, gotOptions);
|
|
413
|
-
try {
|
|
414
|
-
return await this._requestAsBrowser(opts);
|
|
415
|
-
}
|
|
416
|
-
catch (e) {
|
|
417
|
-
if (e instanceof got_scraping_1.TimeoutError) {
|
|
418
|
-
this._handleRequestTimeout(session);
|
|
419
|
-
return undefined;
|
|
420
|
-
}
|
|
421
|
-
throw e;
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
/**
|
|
425
|
-
* Encodes and parses response according to the provided content type
|
|
426
|
-
*/
|
|
427
|
-
async _parseResponse(request, responseStream) {
|
|
428
|
-
const { statusCode } = responseStream;
|
|
429
|
-
const { type, charset } = (0, utils_1.parseContentTypeFromResponse)(responseStream);
|
|
430
|
-
const { response, encoding } = this._encodeResponse(request, responseStream, charset);
|
|
431
|
-
const contentType = { type, encoding };
|
|
432
|
-
if (statusCode >= 500) {
|
|
433
|
-
const body = await (0, utilities_1.readStreamToString)(response, encoding);
|
|
434
|
-
// Errors are often sent as JSON, so attempt to parse them,
|
|
435
|
-
// despite Accept header being set to text/html.
|
|
436
|
-
if (type === APPLICATION_JSON_MIME_TYPE) {
|
|
437
|
-
const errorResponse = JSON.parse(body);
|
|
438
|
-
let { message } = errorResponse;
|
|
439
|
-
if (!message)
|
|
440
|
-
message = util_1.default.inspect(errorResponse, { depth: 1, maxArrayLength: 10 });
|
|
441
|
-
throw new Error(`${statusCode} - ${message}`);
|
|
442
|
-
}
|
|
443
|
-
// It's not a JSON, so it's probably some text. Get the first 100 chars of it.
|
|
444
|
-
throw new Error(`${statusCode} - Internal Server Error: ${body.substr(0, 100)}`);
|
|
445
|
-
}
|
|
446
|
-
else if (HTML_AND_XML_MIME_TYPES.includes(type)) {
|
|
447
|
-
const dom = await this._parseHtmlToDom(response);
|
|
448
|
-
return ({ dom, isXml: type.includes('xml'), response, contentType });
|
|
449
|
-
}
|
|
450
|
-
else {
|
|
451
|
-
const body = await (0, utilities_1.concatStreamToBuffer)(response);
|
|
452
|
-
return { body, response, contentType };
|
|
453
|
-
}
|
|
454
|
-
}
|
|
455
|
-
/**
|
|
456
|
-
* Combines the provided `requestOptions` with mandatory (non-overridable) values.
|
|
457
|
-
*/
|
|
458
|
-
_getRequestOptions(request, session, proxyUrl, gotOptions) {
|
|
459
|
-
const requestOptions = {
|
|
460
|
-
url: request.url,
|
|
461
|
-
method: request.method,
|
|
462
|
-
proxyUrl,
|
|
463
|
-
timeout: { request: this.navigationTimeoutMillis },
|
|
464
|
-
sessionToken: session,
|
|
465
|
-
...gotOptions,
|
|
466
|
-
headers: { ...request.headers, ...gotOptions?.headers },
|
|
467
|
-
https: {
|
|
468
|
-
...gotOptions?.https,
|
|
469
|
-
rejectUnauthorized: !this.ignoreSslErrors,
|
|
470
117
|
},
|
|
471
|
-
isStream: true,
|
|
472
118
|
};
|
|
473
|
-
// Delete any possible lowercased header for cookie as they are merged in _applyCookies under the uppercase Cookie header
|
|
474
|
-
Reflect.deleteProperty(requestOptions.headers, 'cookie');
|
|
475
|
-
// TODO this is incorrect, the check for man in the middle needs to be done
|
|
476
|
-
// on individual proxy level, not on the `proxyConfiguration` level,
|
|
477
|
-
// because users can use normal + MITM proxies in a single configuration.
|
|
478
|
-
// Disable SSL verification for MITM proxies
|
|
479
|
-
if (this.proxyConfiguration && this.proxyConfiguration.isManInTheMiddle) {
|
|
480
|
-
requestOptions.https = {
|
|
481
|
-
...requestOptions.https,
|
|
482
|
-
rejectUnauthorized: false,
|
|
483
|
-
};
|
|
484
|
-
}
|
|
485
|
-
if (/PATCH|POST|PUT/.test(request.method))
|
|
486
|
-
requestOptions.body = request.payload;
|
|
487
|
-
return requestOptions;
|
|
488
|
-
}
|
|
489
|
-
_encodeResponse(request, response, encoding) {
|
|
490
|
-
if (this.forceResponseEncoding) {
|
|
491
|
-
encoding = this.forceResponseEncoding;
|
|
492
|
-
}
|
|
493
|
-
else if (!encoding && this.suggestResponseEncoding) {
|
|
494
|
-
encoding = this.suggestResponseEncoding;
|
|
495
|
-
}
|
|
496
|
-
// Fall back to utf-8 if we still don't have encoding.
|
|
497
|
-
const utf8 = 'utf8';
|
|
498
|
-
if (!encoding)
|
|
499
|
-
return { response, encoding: utf8 };
|
|
500
|
-
// This means that the encoding is one of Node.js supported
|
|
501
|
-
// encodings and we don't need to re-encode it.
|
|
502
|
-
if (Buffer.isEncoding(encoding))
|
|
503
|
-
return { response, encoding };
|
|
504
|
-
// Try to re-encode a variety of unsupported encodings to utf-8
|
|
505
|
-
if (iconv_lite_1.default.encodingExists(encoding)) {
|
|
506
|
-
const encodeStream = iconv_lite_1.default.encodeStream(utf8);
|
|
507
|
-
const decodeStream = iconv_lite_1.default.decodeStream(encoding).on('error', (err) => encodeStream.emit('error', err));
|
|
508
|
-
response.on('error', (err) => decodeStream.emit('error', err));
|
|
509
|
-
const encodedResponse = response.pipe(decodeStream).pipe(encodeStream);
|
|
510
|
-
encodedResponse.statusCode = response.statusCode;
|
|
511
|
-
encodedResponse.headers = response.headers;
|
|
512
|
-
encodedResponse.url = response.url;
|
|
513
|
-
return {
|
|
514
|
-
response: encodedResponse,
|
|
515
|
-
encoding: utf8,
|
|
516
|
-
};
|
|
517
|
-
}
|
|
518
|
-
throw new Error(`Resource ${request.url} served with unsupported charset/encoding: ${encoding}`);
|
|
519
119
|
}
|
|
520
120
|
async _parseHtmlToDom(response) {
|
|
521
121
|
return new Promise((resolve, reject) => {
|
|
@@ -532,73 +132,21 @@ class CheerioCrawler extends basic_1.BasicCrawler {
|
|
|
532
132
|
.pipe(parser);
|
|
533
133
|
});
|
|
534
134
|
}
|
|
535
|
-
/**
|
|
536
|
-
* Checks and extends supported mime types
|
|
537
|
-
*/
|
|
538
|
-
_extendSupportedMimeTypes(additionalMimeTypes) {
|
|
539
|
-
additionalMimeTypes.forEach((mimeType) => {
|
|
540
|
-
try {
|
|
541
|
-
const parsedType = content_type_1.default.parse(mimeType);
|
|
542
|
-
this.supportedMimeTypes.add(parsedType.type);
|
|
543
|
-
}
|
|
544
|
-
catch (err) {
|
|
545
|
-
throw new Error(`Can not parse mime type ${mimeType} from "options.additionalMimeTypes".`);
|
|
546
|
-
}
|
|
547
|
-
});
|
|
548
|
-
}
|
|
549
|
-
/**
|
|
550
|
-
* Handles timeout request
|
|
551
|
-
*/
|
|
552
|
-
_handleRequestTimeout(session) {
|
|
553
|
-
session?.markBad();
|
|
554
|
-
throw new Error(`request timed out after ${this.requestHandlerTimeoutMillis / 1000} seconds.`);
|
|
555
|
-
}
|
|
556
|
-
_abortDownloadOfBody(request, response) {
|
|
557
|
-
const { statusCode } = response;
|
|
558
|
-
const { type } = (0, utils_1.parseContentTypeFromResponse)(response);
|
|
559
|
-
if (statusCode === 406) {
|
|
560
|
-
request.noRetry = true;
|
|
561
|
-
throw new Error(`Resource ${request.url} is not available in the format requested by the Accept header. Skipping resource.`);
|
|
562
|
-
}
|
|
563
|
-
if (!this.supportedMimeTypes.has(type) && statusCode < 500) {
|
|
564
|
-
request.noRetry = true;
|
|
565
|
-
throw new Error(`Resource ${request.url} served Content-Type ${type}, `
|
|
566
|
-
+ `but only ${Array.from(this.supportedMimeTypes).join(', ')} are allowed. Skipping resource.`);
|
|
567
|
-
}
|
|
568
|
-
}
|
|
569
135
|
}
|
|
570
136
|
exports.CheerioCrawler = CheerioCrawler;
|
|
571
|
-
Object.defineProperty(CheerioCrawler, "optionsShape", {
|
|
572
|
-
enumerable: true,
|
|
573
|
-
configurable: true,
|
|
574
|
-
writable: true,
|
|
575
|
-
value: {
|
|
576
|
-
...basic_1.BasicCrawler.optionsShape,
|
|
577
|
-
handlePageFunction: ow_1.default.optional.function,
|
|
578
|
-
navigationTimeoutSecs: ow_1.default.optional.number,
|
|
579
|
-
ignoreSslErrors: ow_1.default.optional.boolean,
|
|
580
|
-
additionalMimeTypes: ow_1.default.optional.array.ofType(ow_1.default.string),
|
|
581
|
-
suggestResponseEncoding: ow_1.default.optional.string,
|
|
582
|
-
forceResponseEncoding: ow_1.default.optional.string,
|
|
583
|
-
proxyConfiguration: ow_1.default.optional.object.validate(core_1.validators.proxyConfiguration),
|
|
584
|
-
persistCookiesPerSession: ow_1.default.optional.boolean,
|
|
585
|
-
preNavigationHooks: ow_1.default.optional.array,
|
|
586
|
-
postNavigationHooks: ow_1.default.optional.array,
|
|
587
|
-
}
|
|
588
|
-
});
|
|
589
137
|
/** @internal */
|
|
590
138
|
async function cheerioCrawlerEnqueueLinks({ options, $, requestQueue, originalRequestUrl, finalRequestUrl }) {
|
|
591
139
|
if (!$) {
|
|
592
140
|
throw new Error('Cannot enqueue links because the DOM is not available.');
|
|
593
141
|
}
|
|
594
|
-
const baseUrl = (0,
|
|
142
|
+
const baseUrl = (0, http_1.resolveBaseUrlForEnqueueLinksFiltering)({
|
|
595
143
|
enqueueStrategy: options?.strategy,
|
|
596
144
|
finalRequestUrl,
|
|
597
145
|
originalRequestUrl,
|
|
598
146
|
userProvidedBaseUrl: options?.baseUrl,
|
|
599
147
|
});
|
|
600
148
|
const urls = extractUrlsFromCheerio($, options?.selector ?? 'a', options?.baseUrl ?? finalRequestUrl ?? originalRequestUrl);
|
|
601
|
-
return (0,
|
|
149
|
+
return (0, http_1.enqueueLinks)({
|
|
602
150
|
requestQueue,
|
|
603
151
|
urls,
|
|
604
152
|
baseUrl,
|
|
@@ -637,41 +185,9 @@ function extractUrlsFromCheerio($, selector, baseUrl) {
|
|
|
637
185
|
.filter((href) => !!href);
|
|
638
186
|
}
|
|
639
187
|
/**
|
|
640
|
-
*
|
|
641
|
-
*
|
|
642
|
-
*
|
|
643
|
-
* got stream. To be able to work with only one stream, we move the expected props
|
|
644
|
-
* from the response stream to the got stream.
|
|
645
|
-
* @internal
|
|
646
|
-
*/
|
|
647
|
-
function addResponsePropertiesToStream(stream) {
|
|
648
|
-
const properties = [
|
|
649
|
-
'statusCode', 'statusMessage', 'headers',
|
|
650
|
-
'complete', 'httpVersion', 'rawHeaders',
|
|
651
|
-
'rawTrailers', 'trailers', 'url',
|
|
652
|
-
'request',
|
|
653
|
-
];
|
|
654
|
-
const response = stream.response;
|
|
655
|
-
response.on('end', () => {
|
|
656
|
-
// @ts-expect-error
|
|
657
|
-
Object.assign(stream.rawTrailers, response.rawTrailers);
|
|
658
|
-
// @ts-expect-error
|
|
659
|
-
Object.assign(stream.trailers, response.trailers);
|
|
660
|
-
// @ts-expect-error
|
|
661
|
-
stream.complete = response.complete;
|
|
662
|
-
});
|
|
663
|
-
for (const prop of properties) {
|
|
664
|
-
if (!(prop in stream)) {
|
|
665
|
-
// @ts-expect-error
|
|
666
|
-
stream[prop] = response[prop];
|
|
667
|
-
}
|
|
668
|
-
}
|
|
669
|
-
return stream;
|
|
670
|
-
}
|
|
671
|
-
/**
|
|
672
|
-
* Creates new {@link Router} instance that works based on request labels.
|
|
673
|
-
* This instance can then serve as a `requestHandler` of your {@link CheerioCrawler}.
|
|
674
|
-
* Defaults to the {@link CheerioCrawlingContext}.
|
|
188
|
+
* Creates new {@apilink Router} instance that works based on request labels.
|
|
189
|
+
* This instance can then serve as a `requestHandler` of your {@apilink CheerioCrawler}.
|
|
190
|
+
* Defaults to the {@apilink CheerioCrawlingContext}.
|
|
675
191
|
*
|
|
676
192
|
* > Serves as a shortcut for using `Router.create<CheerioCrawlingContext>()`.
|
|
677
193
|
*
|
|
@@ -693,7 +209,7 @@ function addResponsePropertiesToStream(stream) {
|
|
|
693
209
|
* ```
|
|
694
210
|
*/
|
|
695
211
|
function createCheerioRouter() {
|
|
696
|
-
return
|
|
212
|
+
return http_1.Router.create();
|
|
697
213
|
}
|
|
698
214
|
exports.createCheerioRouter = createCheerioRouter;
|
|
699
215
|
//# sourceMappingURL=cheerio-crawler.js.map
|