@crawlee/jsdom 4.0.0-beta.168 → 4.0.0-beta.169
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/index.d.ts +1 -0
- package/internals/jsdom-crawler.d.ts +80 -47
- package/internals/jsdom-crawler.js +11 -161
- package/internals/jsdom-parser.d.ts +29 -0
- package/internals/jsdom-parser.js +93 -0
- package/package.json +5 -5
package/index.d.ts
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import {
|
|
1
|
+
import type { CrawlingContext, DOMCrawlingContext, ErrorHandler, GetUserDataFromRequest, HttpCrawlerOptions, InternalHttpHook, RequestHandler, RouterHandler, RouterRoutes, RouteSchemas, RoutesFromSchemas } from '@crawlee/http';
|
|
2
|
+
import { DOMCrawler } from '@crawlee/http';
|
|
3
3
|
import type { Dictionary } from '@crawlee/types';
|
|
4
|
-
import type { CheerioAPI } from 'cheerio';
|
|
5
|
-
import type { DOMWindow } from 'jsdom';
|
|
6
4
|
import { VirtualConsole } from 'jsdom';
|
|
7
5
|
import { z } from 'zod';
|
|
6
|
+
import type { JSDOMParseResult } from './jsdom-parser.js';
|
|
8
7
|
export type JSDOMErrorHandler<UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
|
|
9
8
|
JSONData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
|
|
10
9
|
ContextExtension = Dictionary<never>> = ErrorHandler<CrawlingContext, JSDOMCrawlingContext<UserData, JSONData> & ContextExtension>;
|
|
@@ -23,49 +22,86 @@ Routes extends Record<keyof Routes, Dictionary> = Record<string, UserData>, Stat
|
|
|
23
22
|
export type JSDOMHook<UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
|
|
24
23
|
JSONData extends Dictionary = any> = InternalHttpHook<JSDOMCrawlingContext<UserData, JSONData>>;
|
|
25
24
|
export interface JSDOMCrawlingContext<UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
|
|
26
|
-
JSONData extends Dictionary = any> extends
|
|
27
|
-
window: DOMWindow;
|
|
28
|
-
document: Document;
|
|
29
|
-
body: string;
|
|
30
|
-
/**
|
|
31
|
-
* Wait for an element matching the selector to appear.
|
|
32
|
-
* Timeout defaults to 5s.
|
|
33
|
-
*
|
|
34
|
-
* **Example usage:**
|
|
35
|
-
* ```ts
|
|
36
|
-
* async requestHandler({ waitForSelector, parseWithCheerio }) {
|
|
37
|
-
* await waitForSelector('article h1');
|
|
38
|
-
* const $ = await parseWithCheerio();
|
|
39
|
-
* const title = $('title').text();
|
|
40
|
-
* });
|
|
41
|
-
* ```
|
|
42
|
-
*/
|
|
43
|
-
waitForSelector(selector: string, timeoutMs?: number): Promise<void>;
|
|
44
|
-
/**
|
|
45
|
-
* Returns Cheerio handle, allowing to work with the data same way as with {@link CheerioCrawler}.
|
|
46
|
-
* When provided with the `selector` argument, it will first look for the selector with a 5s timeout.
|
|
47
|
-
*
|
|
48
|
-
* **Example usage:**
|
|
49
|
-
* ```javascript
|
|
50
|
-
* async requestHandler({ parseWithCheerio }) {
|
|
51
|
-
* const $ = await parseWithCheerio();
|
|
52
|
-
* const title = $('title').text();
|
|
53
|
-
* });
|
|
54
|
-
* ```
|
|
55
|
-
*/
|
|
56
|
-
parseWithCheerio(selector?: string, timeoutMs?: number): Promise<CheerioAPI>;
|
|
57
|
-
/**
|
|
58
|
-
* Extracts URLs from the parsed DOM, without adding them to the request queue.
|
|
59
|
-
*/
|
|
60
|
-
extractLinks(options?: ExtractLinksOptions): Promise<string[]>;
|
|
61
|
-
/**
|
|
62
|
-
* Helper function for extracting URLs from the parsed DOM and adding them to the request queue.
|
|
63
|
-
*/
|
|
64
|
-
enqueueLinks(options?: EnqueueLinksOptions): Promise<AddRequestsBatchedResult>;
|
|
25
|
+
JSONData extends Dictionary = any> extends DOMCrawlingContext<JSDOMParseResult, UserData, JSONData> {
|
|
65
26
|
}
|
|
66
27
|
export type JSDOMRequestHandler<UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
|
|
67
28
|
JSONData extends Dictionary = any> = RequestHandler<JSDOMCrawlingContext<UserData, JSONData>>;
|
|
68
|
-
|
|
29
|
+
/**
|
|
30
|
+
* Provides a framework for the parallel crawling of web pages using plain HTTP requests and
|
|
31
|
+
* [jsdom](https://www.npmjs.com/package/jsdom) JSDOM implementation.
|
|
32
|
+
* The URLs to crawl are fed either from a static list of URLs
|
|
33
|
+
* or from a dynamic queue of URLs enabling recursive crawling of websites.
|
|
34
|
+
*
|
|
35
|
+
* Since `JSDOMCrawler` uses raw HTTP requests to download web pages,
|
|
36
|
+
* it is very fast and efficient on data bandwidth. However, if the target website requires JavaScript
|
|
37
|
+
* to display the content, you might need to use {@link PuppeteerCrawler} or {@link PlaywrightCrawler} instead,
|
|
38
|
+
* because it loads the pages using full-featured headless Chrome browser.
|
|
39
|
+
*
|
|
40
|
+
* Alternatively, you can use {@link JSDOMCrawlerOptions.runScripts} to run website scripts in Node.
|
|
41
|
+
* JSDOM does not implement all the standards, so websites can break.
|
|
42
|
+
*
|
|
43
|
+
* **Limitation**:
|
|
44
|
+
* This crawler does not support proxies and cookies yet (each open starts with empty cookie store), and the user agent is always set to `Chrome`.
|
|
45
|
+
*
|
|
46
|
+
* `JSDOMCrawler` downloads each URL using a plain HTTP request,
|
|
47
|
+
* parses the HTML content using [JSDOM](https://www.npmjs.com/package/jsdom)
|
|
48
|
+
* and then invokes the user-provided {@link JSDOMCrawlerOptions.requestHandler} to extract page data
|
|
49
|
+
* using the `window` object.
|
|
50
|
+
*
|
|
51
|
+
* The source URLs are represented using {@link Request} objects that are fed from the
|
|
52
|
+
* {@link IRequestManager|request manager} provided via the {@link JSDOMCrawlerOptions.requestManager|`requestManager`}
|
|
53
|
+
* constructor option (a {@link RequestQueue} is itself a request manager). To read from a read-only source such
|
|
54
|
+
* as a {@link RequestList} while still being able to enqueue new requests, combine it with a queue into a
|
|
55
|
+
* {@link RequestManagerTandem} via {@link IRequestLoader.toTandem|`requestLoader.toTandem()`} and pass the
|
|
56
|
+
* result as `requestManager`.
|
|
57
|
+
*
|
|
58
|
+
* > The {@link JSDOMCrawlerOptions.requestList|`requestList`} and {@link JSDOMCrawlerOptions.requestQueue|`requestQueue`}
|
|
59
|
+
* > options are deprecated; they are still accepted and folded into a single `requestManager` for back-compat.
|
|
60
|
+
*
|
|
61
|
+
* The crawler finishes when there are no more {@link Request} objects to crawl.
|
|
62
|
+
*
|
|
63
|
+
* We can use the `preNavigationHooks` to adjust the crawling context before the request is made:
|
|
64
|
+
*
|
|
65
|
+
* ```
|
|
66
|
+
* preNavigationHooks: [
|
|
67
|
+
* (crawlingContext) => {
|
|
68
|
+
* // ...
|
|
69
|
+
* },
|
|
70
|
+
* ]
|
|
71
|
+
* ```
|
|
72
|
+
*
|
|
73
|
+
* By default, `JSDOMCrawler` only processes web pages with the `text/html`, `application/xhtml+xml`, `text/xml`, `application/xml`,
|
|
74
|
+
* and `application/json` MIME content types (as reported by the `Content-Type` HTTP header),
|
|
75
|
+
* and skips pages with other content types. If you want the crawler to process other content types,
|
|
76
|
+
* use the {@link JSDOMCrawlerOptions.additionalMimeTypes} constructor option.
|
|
77
|
+
* Beware that the parsing behavior differs for HTML, XML, JSON and other types of content.
|
|
78
|
+
* For more details, see {@link JSDOMCrawlerOptions.requestHandler}.
|
|
79
|
+
*
|
|
80
|
+
* New requests are only dispatched when there is enough free CPU and memory available, as judged by the crawler's
|
|
81
|
+
* {@link ConcurrencySystem}.
|
|
82
|
+
* Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the
|
|
83
|
+
* `JSDOMCrawler` constructor, or, for finer control, by injecting a pre-configured
|
|
84
|
+
* {@link ConcurrencySystem|`concurrencySystem`}.
|
|
85
|
+
*
|
|
86
|
+
* **Example usage:**
|
|
87
|
+
*
|
|
88
|
+
* ```javascript
|
|
89
|
+
* const crawler = new JSDOMCrawler({
|
|
90
|
+
* async requestHandler({ request, window }) {
|
|
91
|
+
* await Dataset.pushData({
|
|
92
|
+
* url: request.url,
|
|
93
|
+
* title: window.document.title,
|
|
94
|
+
* });
|
|
95
|
+
* },
|
|
96
|
+
* });
|
|
97
|
+
*
|
|
98
|
+
* await crawler.run([
|
|
99
|
+
* 'http://crawlee.dev',
|
|
100
|
+
* ]);
|
|
101
|
+
* ```
|
|
102
|
+
* @category Crawlers
|
|
103
|
+
*/
|
|
104
|
+
export declare class JSDOMCrawler<ContextExtension = Dictionary<never>, ExtendedContext extends JSDOMCrawlingContext = JSDOMCrawlingContext & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<JSDOMCrawlingContext['request']>>, StatisticStateExtension extends object = {}> extends DOMCrawler<JSDOMParseResult, ContextExtension, ExtendedContext, Routes, StatisticStateExtension> {
|
|
69
105
|
#private;
|
|
70
106
|
/**
|
|
71
107
|
* @internal
|
|
@@ -188,7 +224,6 @@ export declare class JSDOMCrawler<ContextExtension = Dictionary<never>, Extended
|
|
|
188
224
|
hideInternalConsole: z.ZodOptional<z.ZodBoolean>;
|
|
189
225
|
}, z.core.$strict>;
|
|
190
226
|
constructor(options?: JSDOMCrawlerOptions<ContextExtension, ExtendedContext, any, any, Routes, StatisticStateExtension>);
|
|
191
|
-
protected buildContextPipeline(): ContextPipeline<CrawlingContext, JSDOMCrawlingContext>;
|
|
192
227
|
/**
|
|
193
228
|
* Returns the currently used `VirtualConsole` instance. Can be used to listen for the JSDOM's internal console messages.
|
|
194
229
|
*
|
|
@@ -205,8 +240,6 @@ export declare class JSDOMCrawler<ContextExtension = Dictionary<never>, Extended
|
|
|
205
240
|
*/
|
|
206
241
|
getVirtualConsole(): VirtualConsole;
|
|
207
242
|
private readonly jsdomErrorHandler;
|
|
208
|
-
private parseContent;
|
|
209
|
-
private addHelpers;
|
|
210
243
|
}
|
|
211
244
|
/**
|
|
212
245
|
* Creates new {@link Router} instance that works based on request labels.
|
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { JSDOM, ResourceLoader, VirtualConsole } from 'jsdom';
|
|
1
|
+
import { DOMCrawler, HttpCrawler, Router } from '@crawlee/http';
|
|
2
|
+
import { parseArgument } from '@crawlee/utils/internal';
|
|
3
|
+
import { VirtualConsole } from 'jsdom';
|
|
5
4
|
import { z } from 'zod';
|
|
6
|
-
import {
|
|
5
|
+
import { jsdomParser } from './jsdom-parser.js';
|
|
7
6
|
/**
|
|
8
7
|
* Provides a framework for the parallel crawling of web pages using plain HTTP requests and
|
|
9
8
|
* [jsdom](https://www.npmjs.com/package/jsdom) JSDOM implementation.
|
|
@@ -79,12 +78,7 @@ import { addTimeoutToPromise } from '@apify/timeout';
|
|
|
79
78
|
* ```
|
|
80
79
|
* @category Crawlers
|
|
81
80
|
*/
|
|
82
|
-
|
|
83
|
-
// Copy from /packages/browser-pool/src/abstract-classes/browser-plugin.ts:17
|
|
84
|
-
// in order not to include the entire package here
|
|
85
|
-
userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36',
|
|
86
|
-
});
|
|
87
|
-
export class JSDOMCrawler extends HttpCrawler {
|
|
81
|
+
export class JSDOMCrawler extends DOMCrawler {
|
|
88
82
|
/**
|
|
89
83
|
* @internal
|
|
90
84
|
*/
|
|
@@ -95,30 +89,21 @@ export class JSDOMCrawler extends HttpCrawler {
|
|
|
95
89
|
};
|
|
96
90
|
/** @internal */
|
|
97
91
|
static optionsSchema = z.strictObject(JSDOMCrawler.optionsShape);
|
|
98
|
-
#runScripts;
|
|
99
92
|
#hideInternalConsole;
|
|
100
93
|
#virtualConsole = null;
|
|
101
94
|
constructor(options = {}) {
|
|
102
95
|
const { runScripts = false, hideInternalConsole = false, contextPipelineBuilder, ...httpOptions } = parseArgument(options, JSDOMCrawler.optionsSchema, 'JSDOMCrawlerOptions');
|
|
103
96
|
super({
|
|
104
97
|
...httpOptions,
|
|
105
|
-
contextPipelineBuilder
|
|
98
|
+
contextPipelineBuilder,
|
|
99
|
+
parser: jsdomParser({
|
|
100
|
+
runScripts,
|
|
101
|
+
virtualConsole: () => this.getVirtualConsole(),
|
|
102
|
+
log: () => this.log,
|
|
103
|
+
}),
|
|
106
104
|
});
|
|
107
|
-
this.#runScripts = runScripts;
|
|
108
105
|
this.#hideInternalConsole = hideInternalConsole;
|
|
109
106
|
}
|
|
110
|
-
buildContextPipeline() {
|
|
111
|
-
return super
|
|
112
|
-
.buildContextPipeline()
|
|
113
|
-
.compose({
|
|
114
|
-
action: async (context) => await this.parseContent(context),
|
|
115
|
-
cleanup: async (context) => {
|
|
116
|
-
this.getVirtualConsole().off('jsdomError', this.jsdomErrorHandler);
|
|
117
|
-
context.window?.close();
|
|
118
|
-
},
|
|
119
|
-
})
|
|
120
|
-
.compose({ action: async (context) => await this.addHelpers(context) });
|
|
121
|
-
}
|
|
122
107
|
/**
|
|
123
108
|
* Returns the currently used `VirtualConsole` instance. Can be used to listen for the JSDOM's internal console messages.
|
|
124
109
|
*
|
|
@@ -145,141 +130,6 @@ export class JSDOMCrawler extends HttpCrawler {
|
|
|
145
130
|
return this.#virtualConsole;
|
|
146
131
|
}
|
|
147
132
|
jsdomErrorHandler = (error) => this.log.debug('JSDOM error from console', { error });
|
|
148
|
-
async parseContent(crawlingContext) {
|
|
149
|
-
try {
|
|
150
|
-
const isXml = crawlingContext.contentType.type.includes('xml');
|
|
151
|
-
// TODO handle non-string
|
|
152
|
-
const { window } = new JSDOM(crawlingContext.body.toString(), {
|
|
153
|
-
url: crawlingContext.response.url,
|
|
154
|
-
contentType: isXml ? 'text/xml' : 'text/html',
|
|
155
|
-
runScripts: this.#runScripts ? 'dangerously' : undefined,
|
|
156
|
-
resources,
|
|
157
|
-
virtualConsole: this.getVirtualConsole(),
|
|
158
|
-
pretendToBeVisual: true,
|
|
159
|
-
});
|
|
160
|
-
// add some stubs in place of missing API so processing won't fail
|
|
161
|
-
Object.defineProperty(window, 'matchMedia', {
|
|
162
|
-
writable: true,
|
|
163
|
-
value: (query) => ({
|
|
164
|
-
matches: false,
|
|
165
|
-
media: query,
|
|
166
|
-
onchange: null,
|
|
167
|
-
addListener: () => { },
|
|
168
|
-
removeListener: () => { },
|
|
169
|
-
addEventListener: () => { },
|
|
170
|
-
removeEventListener: () => { },
|
|
171
|
-
dispatchEvent: () => { },
|
|
172
|
-
}),
|
|
173
|
-
});
|
|
174
|
-
window.document.createRange = () => {
|
|
175
|
-
const range = new window.Range();
|
|
176
|
-
range.getBoundingClientRect = () => ({});
|
|
177
|
-
range.getClientRects = () => ({ item: () => null, length: 0 });
|
|
178
|
-
return range;
|
|
179
|
-
};
|
|
180
|
-
if (this.#runScripts) {
|
|
181
|
-
try {
|
|
182
|
-
await addTimeoutToPromise(async () => {
|
|
183
|
-
return new Promise((resolve) => {
|
|
184
|
-
window.addEventListener('load', () => {
|
|
185
|
-
resolve();
|
|
186
|
-
}, false);
|
|
187
|
-
}).catch();
|
|
188
|
-
}, 10_000, 'Window.load event not fired after 10 seconds.').catch();
|
|
189
|
-
}
|
|
190
|
-
catch (e) {
|
|
191
|
-
this.log.debug(e.message);
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
return {
|
|
195
|
-
window,
|
|
196
|
-
get body() {
|
|
197
|
-
return window.document.documentElement.outerHTML;
|
|
198
|
-
},
|
|
199
|
-
get document() {
|
|
200
|
-
return window.document;
|
|
201
|
-
},
|
|
202
|
-
};
|
|
203
|
-
}
|
|
204
|
-
catch (err) {
|
|
205
|
-
if (err instanceof NavigationSkippedError) {
|
|
206
|
-
return {
|
|
207
|
-
get window() {
|
|
208
|
-
throw new NavigationSkippedError('The `window` property is not available - `skipNavigation` was used', { cause: err });
|
|
209
|
-
},
|
|
210
|
-
get body() {
|
|
211
|
-
throw new NavigationSkippedError('The `body` property is not available - `skipNavigation` was used', { cause: err });
|
|
212
|
-
},
|
|
213
|
-
get document() {
|
|
214
|
-
throw new NavigationSkippedError('The `document` property is not available - `skipNavigation` was used', { cause: err });
|
|
215
|
-
},
|
|
216
|
-
};
|
|
217
|
-
}
|
|
218
|
-
throw err;
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
async addHelpers(crawlingContext) {
|
|
222
|
-
const addRequests = crawlingContext.addRequests;
|
|
223
|
-
const extractLinks = async (options) => {
|
|
224
|
-
if (!crawlingContext.window) {
|
|
225
|
-
throw new Error('Cannot extract links because the JSDOM is not available.');
|
|
226
|
-
}
|
|
227
|
-
return extractUrlsFromWindow(crawlingContext.window, options?.selector ?? 'a', options?.baseUrl ?? crawlingContext.request.loadedUrl ?? crawlingContext.request.url);
|
|
228
|
-
};
|
|
229
|
-
return {
|
|
230
|
-
extractLinks,
|
|
231
|
-
enqueueLinks: async (options = {}) => {
|
|
232
|
-
const baseUrl = resolveBaseUrlForEnqueueLinksFiltering({
|
|
233
|
-
enqueueStrategy: options.strategy,
|
|
234
|
-
finalRequestUrl: crawlingContext.request.loadedUrl,
|
|
235
|
-
originalRequestUrl: crawlingContext.request.url,
|
|
236
|
-
userProvidedBaseUrl: options.baseUrl,
|
|
237
|
-
});
|
|
238
|
-
const urls = await extractLinks(options);
|
|
239
|
-
return addRequests(urls, {
|
|
240
|
-
...options,
|
|
241
|
-
baseUrl,
|
|
242
|
-
strategy: options.strategy ?? EnqueueStrategy.SameHostname,
|
|
243
|
-
});
|
|
244
|
-
},
|
|
245
|
-
async waitForSelector(selector, timeoutMs = 5_000) {
|
|
246
|
-
const cheerio = await import('cheerio');
|
|
247
|
-
const $ = cheerio.load(crawlingContext.body);
|
|
248
|
-
if ($(selector).get().length === 0) {
|
|
249
|
-
if (timeoutMs) {
|
|
250
|
-
await sleep(50);
|
|
251
|
-
await this.waitForSelector(selector, Math.max(timeoutMs - 50, 0));
|
|
252
|
-
return;
|
|
253
|
-
}
|
|
254
|
-
throw new Error(`Selector '${selector}' not found.`);
|
|
255
|
-
}
|
|
256
|
-
},
|
|
257
|
-
async parseWithCheerio(selector, _timeoutMs = 5_000) {
|
|
258
|
-
const cheerio = await import('cheerio');
|
|
259
|
-
const $ = cheerio.load(crawlingContext.body);
|
|
260
|
-
if (selector && $(selector).get().length === 0) {
|
|
261
|
-
throw new Error(`Selector '${selector}' not found.`);
|
|
262
|
-
}
|
|
263
|
-
return $;
|
|
264
|
-
},
|
|
265
|
-
};
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
/**
|
|
269
|
-
* Extracts URLs from a given Window object.
|
|
270
|
-
* @ignore
|
|
271
|
-
*/
|
|
272
|
-
function extractUrlsFromWindow(window, selector, baseUrl) {
|
|
273
|
-
return Array.from(window.document.querySelectorAll(selector))
|
|
274
|
-
.map((e) => e.href)
|
|
275
|
-
.filter((href) => href !== undefined && href !== '')
|
|
276
|
-
.map((href) => {
|
|
277
|
-
if (href === undefined) {
|
|
278
|
-
return undefined;
|
|
279
|
-
}
|
|
280
|
-
return tryAbsoluteURL(href, baseUrl);
|
|
281
|
-
})
|
|
282
|
-
.filter((href) => href !== undefined && href !== '');
|
|
283
133
|
}
|
|
284
134
|
export function createJSDOMRouter(routesOrSchemas) {
|
|
285
135
|
return Router.create(routesOrSchemas);
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { DOMParser } from '@crawlee/http';
|
|
2
|
+
import type { CrawleeLogger } from '@crawlee/types';
|
|
3
|
+
import type { DOMWindow, VirtualConsole } from 'jsdom';
|
|
4
|
+
export interface JSDOMParseResult {
|
|
5
|
+
window: DOMWindow;
|
|
6
|
+
document: Document;
|
|
7
|
+
body: string;
|
|
8
|
+
}
|
|
9
|
+
export interface JsdomParserOptions {
|
|
10
|
+
/**
|
|
11
|
+
* Download and run scripts.
|
|
12
|
+
*/
|
|
13
|
+
runScripts?: boolean;
|
|
14
|
+
/**
|
|
15
|
+
* Resolves the `VirtualConsole` to hand to JSDOM. Called for every parse, so a crawler can create its console
|
|
16
|
+
* lazily. Defaults to JSDOM's own console handling.
|
|
17
|
+
*/
|
|
18
|
+
virtualConsole?: () => VirtualConsole;
|
|
19
|
+
/**
|
|
20
|
+
* Resolves the logger for JSDOM diagnostics. Called only when there is something to log, so a crawler can hand
|
|
21
|
+
* over its own logger.
|
|
22
|
+
*/
|
|
23
|
+
log?: () => CrawleeLogger;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* A {@link DOMParser} backed by [jsdom](https://www.npmjs.com/package/jsdom). Pass it to a
|
|
27
|
+
* {@link DOMCrawler} to get the crawling context {@link JSDOMCrawler} provides.
|
|
28
|
+
*/
|
|
29
|
+
export declare function jsdomParser(options?: JsdomParserOptions): DOMParser<JSDOMParseResult>;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { tryAbsoluteURL } from '@crawlee/utils/internal';
|
|
2
|
+
import { JSDOM, ResourceLoader } from 'jsdom';
|
|
3
|
+
import { addTimeoutToPromise } from '@apify/timeout';
|
|
4
|
+
const resources = new ResourceLoader({
|
|
5
|
+
// Copy from /packages/browser-pool/src/abstract-classes/browser-plugin.ts:17
|
|
6
|
+
// in order not to include the entire package here
|
|
7
|
+
userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36',
|
|
8
|
+
});
|
|
9
|
+
/**
|
|
10
|
+
* A {@link DOMParser} backed by [jsdom](https://www.npmjs.com/package/jsdom). Pass it to a
|
|
11
|
+
* {@link DOMCrawler} to get the crawling context {@link JSDOMCrawler} provides.
|
|
12
|
+
*/
|
|
13
|
+
export function jsdomParser(options = {}) {
|
|
14
|
+
const { runScripts = false, virtualConsole, log } = options;
|
|
15
|
+
return {
|
|
16
|
+
placeholderMembers: { window: true, document: true, body: true },
|
|
17
|
+
mutable: runScripts,
|
|
18
|
+
async parse(context) {
|
|
19
|
+
const isXml = context.contentType.type.includes('xml');
|
|
20
|
+
// TODO handle non-string
|
|
21
|
+
const { window } = new JSDOM(context.body.toString(), {
|
|
22
|
+
url: context.response.url,
|
|
23
|
+
contentType: isXml ? 'text/xml' : 'text/html',
|
|
24
|
+
runScripts: runScripts ? 'dangerously' : undefined,
|
|
25
|
+
resources,
|
|
26
|
+
virtualConsole: virtualConsole?.(),
|
|
27
|
+
pretendToBeVisual: true,
|
|
28
|
+
});
|
|
29
|
+
// add some stubs in place of missing API so processing won't fail
|
|
30
|
+
Object.defineProperty(window, 'matchMedia', {
|
|
31
|
+
writable: true,
|
|
32
|
+
value: (query) => ({
|
|
33
|
+
matches: false,
|
|
34
|
+
media: query,
|
|
35
|
+
onchange: null,
|
|
36
|
+
addListener: () => { },
|
|
37
|
+
removeListener: () => { },
|
|
38
|
+
addEventListener: () => { },
|
|
39
|
+
removeEventListener: () => { },
|
|
40
|
+
dispatchEvent: () => { },
|
|
41
|
+
}),
|
|
42
|
+
});
|
|
43
|
+
window.document.createRange = () => {
|
|
44
|
+
const range = new window.Range();
|
|
45
|
+
range.getBoundingClientRect = () => ({});
|
|
46
|
+
range.getClientRects = () => ({ item: () => null, length: 0 });
|
|
47
|
+
return range;
|
|
48
|
+
};
|
|
49
|
+
if (runScripts) {
|
|
50
|
+
try {
|
|
51
|
+
await addTimeoutToPromise(async () => {
|
|
52
|
+
return new Promise((resolve) => {
|
|
53
|
+
window.addEventListener('load', () => {
|
|
54
|
+
resolve();
|
|
55
|
+
}, false);
|
|
56
|
+
}).catch();
|
|
57
|
+
}, 10_000, 'Window.load event not fired after 10 seconds.').catch();
|
|
58
|
+
}
|
|
59
|
+
catch (e) {
|
|
60
|
+
log?.().debug(e.message);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
window,
|
|
65
|
+
get body() {
|
|
66
|
+
return window.document.documentElement.outerHTML;
|
|
67
|
+
},
|
|
68
|
+
get document() {
|
|
69
|
+
return window.document;
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
},
|
|
73
|
+
extractLinks: ({ window }, selector, baseUrl) => extractUrlsFromWindow(window, selector, baseUrl),
|
|
74
|
+
select: ({ document }, selector) => document.querySelectorAll(selector),
|
|
75
|
+
cleanup: ({ window }) => window.close(),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Extracts URLs from a given Window object.
|
|
80
|
+
* @ignore
|
|
81
|
+
*/
|
|
82
|
+
function extractUrlsFromWindow(window, selector, baseUrl) {
|
|
83
|
+
return Array.from(window.document.querySelectorAll(selector))
|
|
84
|
+
.map((e) => e.href)
|
|
85
|
+
.filter((href) => href !== undefined && href !== '')
|
|
86
|
+
.map((href) => {
|
|
87
|
+
if (href === undefined) {
|
|
88
|
+
return undefined;
|
|
89
|
+
}
|
|
90
|
+
return tryAbsoluteURL(href, baseUrl);
|
|
91
|
+
})
|
|
92
|
+
.filter((href) => href !== undefined && href !== '');
|
|
93
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crawlee/jsdom",
|
|
3
|
-
"version": "4.0.0-beta.
|
|
3
|
+
"version": "4.0.0-beta.169",
|
|
4
4
|
"description": "The scalable web crawling and scraping library for JavaScript/Node.js. Enables development of data extraction and web automation jobs (not only) with headless Chrome and Puppeteer.",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=22.0.0"
|
|
@@ -49,9 +49,9 @@
|
|
|
49
49
|
"dependencies": {
|
|
50
50
|
"@apify/timeout": "^1.0.1",
|
|
51
51
|
"@apify/utilities": "^3.0.1",
|
|
52
|
-
"@crawlee/http": "4.0.0-beta.
|
|
53
|
-
"@crawlee/types": "4.0.0-beta.
|
|
54
|
-
"@crawlee/utils": "4.0.0-beta.
|
|
52
|
+
"@crawlee/http": "4.0.0-beta.169",
|
|
53
|
+
"@crawlee/types": "4.0.0-beta.169",
|
|
54
|
+
"@crawlee/utils": "4.0.0-beta.169",
|
|
55
55
|
"@types/jsdom": "^21.1.7",
|
|
56
56
|
"cheerio": "^1.0.0",
|
|
57
57
|
"jsdom": "^26.1.0",
|
|
@@ -65,5 +65,5 @@
|
|
|
65
65
|
}
|
|
66
66
|
}
|
|
67
67
|
},
|
|
68
|
-
"gitHead": "
|
|
68
|
+
"gitHead": "a42dc93fa0ef68180d83ab12af362082690f73e2"
|
|
69
69
|
}
|