@crawlee/http 4.0.0-beta.17 → 4.0.0-beta.171
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 +14 -14
- package/index.d.ts +1 -1
- package/index.js +1 -1
- package/internals/dom-crawler.d.ts +131 -0
- package/internals/dom-crawler.js +97 -0
- package/internals/file-download.d.ts +14 -12
- package/internals/file-download.js +47 -43
- package/internals/http-crawler.d.ts +211 -270
- package/internals/http-crawler.js +258 -248
- package/internals/utils.d.ts +11 -1
- package/internals/utils.js +50 -6
- package/package.json +13 -12
- package/index.d.ts.map +0 -1
- package/index.js.map +0 -1
- package/internals/file-download.d.ts.map +0 -1
- package/internals/file-download.js.map +0 -1
- package/internals/http-crawler.d.ts.map +0 -1
- package/internals/http-crawler.js.map +0 -1
- package/internals/utils.d.ts.map +0 -1
- package/internals/utils.js.map +0 -1
package/README.md
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
<h1 align="center">
|
|
2
2
|
<a href="https://crawlee.dev">
|
|
3
3
|
<picture>
|
|
4
|
-
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-dark.svg?sanitize=true"
|
|
5
|
-
<img alt="Crawlee" src="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-light.svg?sanitize=true" width="500"
|
|
4
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-dark.svg?sanitize=true" />
|
|
5
|
+
<img alt="Crawlee" src="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-light.svg?sanitize=true" width="500" />
|
|
6
6
|
</picture>
|
|
7
7
|
</a>
|
|
8
|
-
<br
|
|
8
|
+
<br />
|
|
9
9
|
<small>A web scraping and browser automation library</small>
|
|
10
10
|
</h1>
|
|
11
11
|
|
|
12
|
-
<p align=center>
|
|
13
|
-
<a href="https://trendshift.io/repositories/5179" target="_blank"><img src="https://trendshift.io/api/badge/repositories/5179" alt="apify%2Fcrawlee | Trendshift"
|
|
12
|
+
<p align="center">
|
|
13
|
+
<a href="https://trendshift.io/repositories/5179" target="_blank"><img src="https://trendshift.io/api/badge/repositories/5179" alt="apify%2Fcrawlee | Trendshift" width="250" height="55"/></a>
|
|
14
14
|
</p>
|
|
15
15
|
|
|
16
|
-
<p align=center>
|
|
17
|
-
<a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/v/@crawlee/core.svg" alt="NPM latest version" data-canonical-src="https://img.shields.io/npm/v/@crawlee/core/next.svg"
|
|
18
|
-
<a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/dm/@crawlee/core.svg" alt="Downloads" data-canonical-src="https://img.shields.io/npm/dm/@crawlee/core.svg"
|
|
19
|
-
<a href="https://discord.gg/jyEM2PRvMU" rel="nofollow"><img src="https://img.shields.io/discord/801163717915574323?label=discord" alt="Chat on discord" data-canonical-src="https://img.shields.io/discord/801163717915574323?label=discord"
|
|
20
|
-
<a href="https://github.com/apify/crawlee/actions/workflows/test-ci.yml"><img src="https://github.com/apify/crawlee/actions/workflows/test-ci.yml/badge.svg?branch=master" alt="Build Status"
|
|
16
|
+
<p align="center">
|
|
17
|
+
<a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/v/@crawlee/core.svg" alt="NPM latest version" data-canonical-src="https://img.shields.io/npm/v/@crawlee/core/next.svg" /></a>
|
|
18
|
+
<a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/dm/@crawlee/core.svg" alt="Downloads" data-canonical-src="https://img.shields.io/npm/dm/@crawlee/core.svg" /></a>
|
|
19
|
+
<a href="https://discord.gg/jyEM2PRvMU" rel="nofollow"><img src="https://img.shields.io/discord/801163717915574323?label=discord" alt="Chat on discord" data-canonical-src="https://img.shields.io/discord/801163717915574323?label=discord" /></a>
|
|
20
|
+
<a href="https://github.com/apify/crawlee/actions/workflows/test-ci.yml"><img src="https://github.com/apify/crawlee/actions/workflows/test-ci.yml/badge.svg?branch=master" alt="Build Status" /></a>
|
|
21
21
|
</p>
|
|
22
22
|
|
|
23
23
|
Crawlee covers your crawling and scraping end-to-end and **helps you build reliable scrapers. Fast.**
|
|
@@ -89,7 +89,7 @@ By default, Crawlee stores data to `./storage` in the current working directory.
|
|
|
89
89
|
We provide automated beta builds for every merged code change in Crawlee. You can find them in the npm [list of releases](https://www.npmjs.com/package/crawlee?activeTab=versions). If you want to test new features or bug fixes before we release them, feel free to install a beta build like this:
|
|
90
90
|
|
|
91
91
|
```bash
|
|
92
|
-
npm install crawlee@
|
|
92
|
+
npm install crawlee@next
|
|
93
93
|
```
|
|
94
94
|
|
|
95
95
|
If you also use the [Apify SDK](https://github.com/apify/apify-sdk-js), you need to specify dependency overrides in your `package.json` file so that you don't end up with multiple versions of Crawlee installed:
|
|
@@ -98,9 +98,9 @@ If you also use the [Apify SDK](https://github.com/apify/apify-sdk-js), you need
|
|
|
98
98
|
{
|
|
99
99
|
"overrides": {
|
|
100
100
|
"apify": {
|
|
101
|
-
"@crawlee/core": "
|
|
102
|
-
"@crawlee/types": "
|
|
103
|
-
"@crawlee/utils": "
|
|
101
|
+
"@crawlee/core": "$crawlee",
|
|
102
|
+
"@crawlee/types": "$crawlee",
|
|
103
|
+
"@crawlee/utils": "$crawlee"
|
|
104
104
|
}
|
|
105
105
|
}
|
|
106
106
|
}
|
package/index.d.ts
CHANGED
package/index.js
CHANGED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import type { AddRequestsBatchedResult, ContextPipeline, CrawlingContext, EnqueueLinksOptions, ExtractLinksOptions, GetUserDataFromRequest } from '@crawlee/basic';
|
|
2
|
+
import type { Awaitable, Dictionary } from '@crawlee/types';
|
|
3
|
+
import type { CheerioAPI } from 'cheerio';
|
|
4
|
+
import type { HttpCrawlerOptions, InternalHttpCrawlingContext } from './http-crawler.js';
|
|
5
|
+
import { HttpCrawler } from './http-crawler.js';
|
|
6
|
+
/**
|
|
7
|
+
* The minimum a {@link DOMParser} has to contribute to the crawling context - the serialized document, used by
|
|
8
|
+
* the {@link DOMCrawlingContext.parseWithCheerio|`parseWithCheerio`} helper.
|
|
9
|
+
*/
|
|
10
|
+
export interface DOMParseResult {
|
|
11
|
+
body: string;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Turns a response body into a DOM representation and knows how to query it. Passing one to {@link DOMCrawler}
|
|
15
|
+
* is what makes the crawler jsdom-based, linkedom-based, or based on a DOM implementation of your own.
|
|
16
|
+
*
|
|
17
|
+
* **Example usage:**
|
|
18
|
+
* ```ts
|
|
19
|
+
* import { DOMCrawler } from 'crawlee';
|
|
20
|
+
* import type { DOMParser } from 'crawlee';
|
|
21
|
+
*
|
|
22
|
+
* const myParser: DOMParser<{ body: string }> = {
|
|
23
|
+
* // ...
|
|
24
|
+
* };
|
|
25
|
+
*
|
|
26
|
+
* const crawler = new DOMCrawler({
|
|
27
|
+
* parser: myParser,
|
|
28
|
+
* async requestHandler({ body }) {
|
|
29
|
+
* // ...
|
|
30
|
+
* },
|
|
31
|
+
* });
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
export interface DOMParser<Parsed extends DOMParseResult> {
|
|
35
|
+
/**
|
|
36
|
+
* The context members {@link DOMParser.parse|`parse`} contributes, mapped to `true`. Used to build the
|
|
37
|
+
* placeholders that report a helpful error when the members are accessed after `skipNavigation` - the `Record`
|
|
38
|
+
* type forces every key of `Parsed` to be listed, so the compiler catches an omission that would otherwise
|
|
39
|
+
* yield `undefined` (rather than throwing) after `skipNavigation`.
|
|
40
|
+
*/
|
|
41
|
+
readonly placeholderMembers: Record<keyof Parsed & string, true>;
|
|
42
|
+
parse(context: InternalHttpCrawlingContext): Awaitable<Parsed>;
|
|
43
|
+
/**
|
|
44
|
+
* Returns the URLs the `selector` matches, resolved against `baseUrl`.
|
|
45
|
+
*/
|
|
46
|
+
extractLinks(parsed: Parsed, selector: string, baseUrl: string): Awaitable<string[]>;
|
|
47
|
+
/**
|
|
48
|
+
* Returns the current matches of `selector`. Only the count is used, by
|
|
49
|
+
* {@link DOMCrawlingContext.waitForSelector|`waitForSelector`}.
|
|
50
|
+
*/
|
|
51
|
+
select(parsed: Parsed, selector: string): Awaitable<ArrayLike<unknown>>;
|
|
52
|
+
/**
|
|
53
|
+
* Whether the parse result can change after {@link DOMParser.parse|`parse`} returned - the case when the DOM
|
|
54
|
+
* implementation runs the page scripts. If it can, {@link DOMCrawlingContext.waitForSelector|`waitForSelector`}
|
|
55
|
+
* polls until the timeout elapses; otherwise it fails as soon as the selector does not match.
|
|
56
|
+
*/
|
|
57
|
+
readonly mutable?: boolean;
|
|
58
|
+
/**
|
|
59
|
+
* Returns a Cheerio handle over the parse result, for parsers that are backed by Cheerio anyway. Without it,
|
|
60
|
+
* {@link DOMCrawlingContext.parseWithCheerio|`parseWithCheerio`} parses
|
|
61
|
+
* {@link DOMParseResult.body|`body`} again.
|
|
62
|
+
*/
|
|
63
|
+
toCheerio?(parsed: Parsed): Awaitable<CheerioAPI>;
|
|
64
|
+
/**
|
|
65
|
+
* Releases whatever {@link DOMParser.parse|`parse`} allocated. Called after the request handler finishes or
|
|
66
|
+
* fails, and skipped entirely when navigation was skipped.
|
|
67
|
+
*/
|
|
68
|
+
cleanup?(parsed: Parsed): Awaitable<void>;
|
|
69
|
+
}
|
|
70
|
+
export interface DOMCrawlingHelpers {
|
|
71
|
+
/**
|
|
72
|
+
* Extracts URLs from the parsed DOM, without adding them to the request queue.
|
|
73
|
+
*/
|
|
74
|
+
extractLinks(options?: ExtractLinksOptions): Promise<string[]>;
|
|
75
|
+
/**
|
|
76
|
+
* Helper function for extracting URLs from the parsed DOM and adding them to the request queue.
|
|
77
|
+
*/
|
|
78
|
+
enqueueLinks(options?: EnqueueLinksOptions): Promise<AddRequestsBatchedResult>;
|
|
79
|
+
/**
|
|
80
|
+
* Wait for an element matching the selector to appear. The `timeoutMs` only has an effect when the parser is
|
|
81
|
+
* {@link DOMParser.mutable|`mutable`} (e.g. {@link JSDOMCrawler} with `runScripts: true`); otherwise the
|
|
82
|
+
* selector is checked once and the call resolves or throws immediately.
|
|
83
|
+
* Timeout defaults to 5s.
|
|
84
|
+
*
|
|
85
|
+
* **Example usage:**
|
|
86
|
+
* ```ts
|
|
87
|
+
* async requestHandler({ waitForSelector, parseWithCheerio }) {
|
|
88
|
+
* await waitForSelector('article h1');
|
|
89
|
+
* const $ = await parseWithCheerio();
|
|
90
|
+
* const title = $('title').text();
|
|
91
|
+
* });
|
|
92
|
+
* ```
|
|
93
|
+
*/
|
|
94
|
+
waitForSelector(selector: string, timeoutMs?: number): Promise<void>;
|
|
95
|
+
/**
|
|
96
|
+
* Returns Cheerio handle, allowing to work with the data same way as with {@link CheerioCrawler}.
|
|
97
|
+
* When provided with the `selector` argument, it will throw if it's not available.
|
|
98
|
+
*
|
|
99
|
+
* **Example usage:**
|
|
100
|
+
* ```javascript
|
|
101
|
+
* async requestHandler({ parseWithCheerio }) {
|
|
102
|
+
* const $ = await parseWithCheerio();
|
|
103
|
+
* const title = $('title').text();
|
|
104
|
+
* });
|
|
105
|
+
* ```
|
|
106
|
+
*/
|
|
107
|
+
parseWithCheerio(selector?: string, timeoutMs?: number): Promise<CheerioAPI>;
|
|
108
|
+
}
|
|
109
|
+
export type DOMCrawlingContext<Parsed extends DOMParseResult = DOMParseResult, UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
|
|
110
|
+
JSONData extends Dictionary = any> = InternalHttpCrawlingContext<UserData, JSONData> & Parsed & DOMCrawlingHelpers;
|
|
111
|
+
export interface DOMCrawlerOptions<Parsed extends DOMParseResult = DOMParseResult, ContextExtension = Dictionary<never>, ExtendedContext extends DOMCrawlingContext<Parsed> = DOMCrawlingContext<Parsed> & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, any>, StatisticStateExtension extends object = {}> extends HttpCrawlerOptions<DOMCrawlingContext<Parsed>, ContextExtension, ExtendedContext, Routes, StatisticStateExtension> {
|
|
112
|
+
/**
|
|
113
|
+
* The DOM implementation to parse the response bodies with. Its parse result becomes part of the crawling
|
|
114
|
+
* context, so the members the request handler receives follow from the parser you pass.
|
|
115
|
+
*/
|
|
116
|
+
parser: DOMParser<Parsed>;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* An {@link HttpCrawler} that parses each response into a DOM using the {@link DOMCrawlerOptions.parser|`parser`}
|
|
120
|
+
* it is given, and exposes the parse result plus the {@link DOMCrawlingContext.enqueueLinks|`enqueueLinks`} and
|
|
121
|
+
* {@link DOMCrawlingContext.extractLinks|`extractLinks`} helpers on the crawling context.
|
|
122
|
+
*
|
|
123
|
+
* {@link JSDOMCrawler} and {@link LinkeDOMCrawler} are this crawler with a parser already chosen.
|
|
124
|
+
*
|
|
125
|
+
* @category Crawlers
|
|
126
|
+
*/
|
|
127
|
+
export declare class DOMCrawler<Parsed extends DOMParseResult = DOMParseResult, ContextExtension = Dictionary<never>, ExtendedContext extends DOMCrawlingContext<Parsed> = DOMCrawlingContext<Parsed> & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<DOMCrawlingContext<Parsed>['request']>>, StatisticStateExtension extends object = {}> extends HttpCrawler<DOMCrawlingContext<Parsed>, ContextExtension, ExtendedContext, Routes, StatisticStateExtension> {
|
|
128
|
+
#private;
|
|
129
|
+
constructor(options: DOMCrawlerOptions<Parsed, ContextExtension, ExtendedContext, Routes, StatisticStateExtension>);
|
|
130
|
+
protected buildContextPipeline(): ContextPipeline<CrawlingContext, DOMCrawlingContext<Parsed>>;
|
|
131
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { EnqueueStrategy, NavigationSkippedError, resolveBaseUrlForEnqueueLinksFiltering } from '@crawlee/basic';
|
|
2
|
+
import { sleep } from '@crawlee/utils';
|
|
3
|
+
import { HttpCrawler } from './http-crawler.js';
|
|
4
|
+
/**
|
|
5
|
+
* An {@link HttpCrawler} that parses each response into a DOM using the {@link DOMCrawlerOptions.parser|`parser`}
|
|
6
|
+
* it is given, and exposes the parse result plus the {@link DOMCrawlingContext.enqueueLinks|`enqueueLinks`} and
|
|
7
|
+
* {@link DOMCrawlingContext.extractLinks|`extractLinks`} helpers on the crawling context.
|
|
8
|
+
*
|
|
9
|
+
* {@link JSDOMCrawler} and {@link LinkeDOMCrawler} are this crawler with a parser already chosen.
|
|
10
|
+
*
|
|
11
|
+
* @category Crawlers
|
|
12
|
+
*/
|
|
13
|
+
export class DOMCrawler extends HttpCrawler {
|
|
14
|
+
#parser;
|
|
15
|
+
constructor(options) {
|
|
16
|
+
const { parser, contextPipelineBuilder, ...rest } = options;
|
|
17
|
+
super({
|
|
18
|
+
...rest,
|
|
19
|
+
contextPipelineBuilder: contextPipelineBuilder ?? (() => this.buildContextPipeline()),
|
|
20
|
+
});
|
|
21
|
+
this.#parser = parser;
|
|
22
|
+
}
|
|
23
|
+
buildContextPipeline() {
|
|
24
|
+
return super
|
|
25
|
+
.buildContextPipeline()
|
|
26
|
+
.compose({
|
|
27
|
+
action: async (context) => this.#parseContent(context),
|
|
28
|
+
cleanup: async (context) => {
|
|
29
|
+
// The `skipNavigation` placeholders below throw on access, so there is nothing to clean up.
|
|
30
|
+
if (!context.request.skipNavigation) {
|
|
31
|
+
await this.#parser.cleanup?.(context);
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
})
|
|
35
|
+
.compose({ action: async (context) => this.#addHelpers(context) });
|
|
36
|
+
}
|
|
37
|
+
async #parseContent(context) {
|
|
38
|
+
try {
|
|
39
|
+
return await this.#parser.parse(context);
|
|
40
|
+
}
|
|
41
|
+
catch (err) {
|
|
42
|
+
if (err instanceof NavigationSkippedError) {
|
|
43
|
+
return Object.defineProperties({}, Object.fromEntries(Object.keys(this.#parser.placeholderMembers).map((member) => [
|
|
44
|
+
member,
|
|
45
|
+
{
|
|
46
|
+
configurable: true,
|
|
47
|
+
enumerable: true,
|
|
48
|
+
get() {
|
|
49
|
+
throw new NavigationSkippedError(`The \`${member}\` property is not available - \`skipNavigation\` was used`, { cause: err });
|
|
50
|
+
},
|
|
51
|
+
},
|
|
52
|
+
])));
|
|
53
|
+
}
|
|
54
|
+
throw err;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
async #addHelpers(context) {
|
|
58
|
+
const { addRequests } = context;
|
|
59
|
+
const parser = this.#parser;
|
|
60
|
+
const extractLinks = async (options) => parser.extractLinks(context, options?.selector ?? 'a', options?.baseUrl ?? context.request.loadedUrl ?? context.request.url);
|
|
61
|
+
const waitForSelector = async (selector, timeoutMs = 5_000) => {
|
|
62
|
+
let remaining = parser.mutable ? timeoutMs : 0;
|
|
63
|
+
while ((await parser.select(context, selector)).length === 0) {
|
|
64
|
+
if (remaining <= 0) {
|
|
65
|
+
throw new Error(`Selector '${selector}' not found.`);
|
|
66
|
+
}
|
|
67
|
+
await sleep(50);
|
|
68
|
+
remaining -= 50;
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
return {
|
|
72
|
+
extractLinks,
|
|
73
|
+
waitForSelector,
|
|
74
|
+
enqueueLinks: async (options = {}) => {
|
|
75
|
+
const baseUrl = resolveBaseUrlForEnqueueLinksFiltering({
|
|
76
|
+
enqueueStrategy: options.strategy,
|
|
77
|
+
finalRequestUrl: context.request.loadedUrl,
|
|
78
|
+
originalRequestUrl: context.request.url,
|
|
79
|
+
userProvidedBaseUrl: options.baseUrl,
|
|
80
|
+
});
|
|
81
|
+
const urls = await extractLinks(options);
|
|
82
|
+
return addRequests(urls, {
|
|
83
|
+
...options,
|
|
84
|
+
baseUrl,
|
|
85
|
+
strategy: options.strategy ?? EnqueueStrategy.SameHostname,
|
|
86
|
+
});
|
|
87
|
+
},
|
|
88
|
+
async parseWithCheerio(selector, _timeoutMs = 5_000) {
|
|
89
|
+
const $ = (await parser.toCheerio?.(context)) ?? (await import('cheerio')).load(context.body);
|
|
90
|
+
if (selector && $(selector).get().length === 0) {
|
|
91
|
+
throw new Error(`Selector '${selector}' not found.`);
|
|
92
|
+
}
|
|
93
|
+
return $;
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { Transform } from 'node:stream';
|
|
2
|
-
import type { BasicCrawlerOptions } from '@crawlee/basic';
|
|
2
|
+
import type { BasicCrawlerOptions, ContextPipeline, CrawlingContext, LoadedRequest } from '@crawlee/basic';
|
|
3
3
|
import { BasicCrawler } from '@crawlee/basic';
|
|
4
|
-
import type {
|
|
4
|
+
import type { Request } from '@crawlee/core';
|
|
5
5
|
import type { Dictionary } from '@crawlee/types';
|
|
6
|
-
import type { ErrorHandler, GetUserDataFromRequest, InternalHttpHook, RequestHandler, RouterRoutes } from '../index.js';
|
|
7
|
-
export type FileDownloadErrorHandler<UserData extends Dictionary = any
|
|
6
|
+
import type { ErrorHandler, GetUserDataFromRequest, InternalHttpHook, RequestHandler, RouterHandler, RouterRoutes, RouteSchemas, RoutesFromSchemas } from '../index.js';
|
|
7
|
+
export type FileDownloadErrorHandler<UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
|
|
8
|
+
ContextExtension = Dictionary<never>> = ErrorHandler<CrawlingContext, FileDownloadCrawlingContext<UserData> & ContextExtension>;
|
|
8
9
|
export type FileDownloadHook<UserData extends Dictionary = any> = InternalHttpHook<FileDownloadCrawlingContext<UserData>>;
|
|
9
10
|
export interface FileDownloadCrawlingContext<UserData extends Dictionary = any> extends CrawlingContext<UserData> {
|
|
10
11
|
request: LoadedRequest<Request<UserData>>;
|
|
@@ -49,23 +50,23 @@ export declare function ByteCounterStream({ logTransferredBytes, loggingInterval
|
|
|
49
50
|
*
|
|
50
51
|
* `FileCrawler` downloads each URL using a plain HTTP request and then invokes the user-provided {@link FileDownloadOptions.requestHandler} where the user can specify what to do with the downloaded data.
|
|
51
52
|
*
|
|
52
|
-
* The source URLs are represented using {@link Request} objects that are fed from {@link
|
|
53
|
+
* The source URLs are represented using {@link Request} objects that are fed from the {@link IRequestManager|request manager} provided via the {@link FileDownloadOptions.requestManager|`requestManager`} constructor option (a {@link RequestQueue} is itself a request manager). To read from a read-only source such as a {@link RequestList} while still being able to enqueue new requests, combine it with a queue into a {@link RequestManagerTandem} via {@link IRequestLoader.toTandem|`requestLoader.toTandem()`} and pass the result as `requestManager`.
|
|
53
54
|
*
|
|
54
|
-
*
|
|
55
|
+
* > The {@link FileDownloadOptions.requestList|`requestList`} and {@link FileDownloadOptions.requestQueue|`requestQueue`} options are deprecated; they are still accepted and folded into a single `requestManager` for back-compat.
|
|
55
56
|
*
|
|
56
57
|
* The crawler finishes when there are no more {@link Request} objects to crawl.
|
|
57
58
|
*
|
|
58
|
-
* We can use the `preNavigationHooks` to adjust
|
|
59
|
+
* We can use the `preNavigationHooks` to adjust the crawling context before the request is made:
|
|
59
60
|
*
|
|
60
61
|
* ```
|
|
61
62
|
* preNavigationHooks: [
|
|
62
|
-
* (crawlingContext
|
|
63
|
+
* (crawlingContext) => {
|
|
63
64
|
* // ...
|
|
64
65
|
* },
|
|
65
66
|
* ]
|
|
66
67
|
* ```
|
|
67
68
|
*
|
|
68
|
-
* New requests are only dispatched when there is enough free CPU and memory available,
|
|
69
|
+
* New requests are only dispatched when there is enough free CPU and memory available, as judged by the crawler's {@link ConcurrencySystem}. Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the `FileCrawler` constructor, or, for finer control, by injecting a pre-configured {@link ConcurrencySystem|`concurrencySystem`}.
|
|
69
70
|
*
|
|
70
71
|
* ## Example usage
|
|
71
72
|
*
|
|
@@ -85,6 +86,7 @@ export declare function ByteCounterStream({ logTransferredBytes, loggingInterval
|
|
|
85
86
|
*/
|
|
86
87
|
export declare class FileDownload extends BasicCrawler<FileDownloadCrawlingContext> {
|
|
87
88
|
constructor(options?: BasicCrawlerOptions<FileDownloadCrawlingContext>);
|
|
89
|
+
protected buildContextPipeline(): ContextPipeline<CrawlingContext, FileDownloadCrawlingContext>;
|
|
88
90
|
private initiateDownload;
|
|
89
91
|
}
|
|
90
92
|
/**
|
|
@@ -111,6 +113,6 @@ export declare class FileDownload extends BasicCrawler<FileDownloadCrawlingConte
|
|
|
111
113
|
* await crawler.run();
|
|
112
114
|
* ```
|
|
113
115
|
*/
|
|
114
|
-
|
|
115
|
-
export declare function createFileRouter<Context extends FileDownloadCrawlingContext = FileDownloadCrawlingContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, UserData
|
|
116
|
-
|
|
116
|
+
export declare function createFileRouter<Context extends FileDownloadCrawlingContext = FileDownloadCrawlingContext, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<Context['request']>>>(routes?: RouterRoutes<Context, Routes>): RouterHandler<Context, Routes>;
|
|
117
|
+
export declare function createFileRouter<Context extends FileDownloadCrawlingContext = FileDownloadCrawlingContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, Record<string, UserData>>): RouterHandler<Context, Record<string, UserData>>;
|
|
118
|
+
export declare function createFileRouter<Context extends FileDownloadCrawlingContext = FileDownloadCrawlingContext, const Schemas extends RouteSchemas = RouteSchemas>(schemas: Schemas): RouterHandler<Context, RoutesFromSchemas<Schemas>>;
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { Transform } from 'node:stream';
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { BasicCrawler } from '@crawlee/basic';
|
|
3
|
+
import { ResponseWithUrl } from '@crawlee/http-client';
|
|
4
4
|
import { Router } from '../index.js';
|
|
5
5
|
import { parseContentTypeFromResponse } from './utils.js';
|
|
6
|
+
const kBodyDrained = Symbol('bodyDrained');
|
|
6
7
|
/**
|
|
7
8
|
* Creates a transform stream that throws an error if the source data speed is below the specified minimum speed.
|
|
8
9
|
* This `Transform` checks the amount of data every `checkProgressInterval` milliseconds.
|
|
@@ -70,23 +71,23 @@ export function ByteCounterStream({ logTransferredBytes, loggingInterval = 5000,
|
|
|
70
71
|
*
|
|
71
72
|
* `FileCrawler` downloads each URL using a plain HTTP request and then invokes the user-provided {@link FileDownloadOptions.requestHandler} where the user can specify what to do with the downloaded data.
|
|
72
73
|
*
|
|
73
|
-
* The source URLs are represented using {@link Request} objects that are fed from {@link
|
|
74
|
+
* The source URLs are represented using {@link Request} objects that are fed from the {@link IRequestManager|request manager} provided via the {@link FileDownloadOptions.requestManager|`requestManager`} constructor option (a {@link RequestQueue} is itself a request manager). To read from a read-only source such as a {@link RequestList} while still being able to enqueue new requests, combine it with a queue into a {@link RequestManagerTandem} via {@link IRequestLoader.toTandem|`requestLoader.toTandem()`} and pass the result as `requestManager`.
|
|
74
75
|
*
|
|
75
|
-
*
|
|
76
|
+
* > The {@link FileDownloadOptions.requestList|`requestList`} and {@link FileDownloadOptions.requestQueue|`requestQueue`} options are deprecated; they are still accepted and folded into a single `requestManager` for back-compat.
|
|
76
77
|
*
|
|
77
78
|
* The crawler finishes when there are no more {@link Request} objects to crawl.
|
|
78
79
|
*
|
|
79
|
-
* We can use the `preNavigationHooks` to adjust
|
|
80
|
+
* We can use the `preNavigationHooks` to adjust the crawling context before the request is made:
|
|
80
81
|
*
|
|
81
82
|
* ```
|
|
82
83
|
* preNavigationHooks: [
|
|
83
|
-
* (crawlingContext
|
|
84
|
+
* (crawlingContext) => {
|
|
84
85
|
* // ...
|
|
85
86
|
* },
|
|
86
87
|
* ]
|
|
87
88
|
* ```
|
|
88
89
|
*
|
|
89
|
-
* New requests are only dispatched when there is enough free CPU and memory available,
|
|
90
|
+
* New requests are only dispatched when there is enough free CPU and memory available, as judged by the crawler's {@link ConcurrencySystem}. Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the `FileCrawler` constructor, or, for finer control, by injecting a pre-configured {@link ConcurrencySystem|`concurrencySystem`}.
|
|
90
91
|
*
|
|
91
92
|
* ## Example usage
|
|
92
93
|
*
|
|
@@ -109,55 +110,58 @@ export class FileDownload extends BasicCrawler {
|
|
|
109
110
|
constructor(options = {}) {
|
|
110
111
|
super({
|
|
111
112
|
...options,
|
|
112
|
-
contextPipelineBuilder: () =>
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
113
|
+
contextPipelineBuilder: () => this.buildContextPipeline(),
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
buildContextPipeline() {
|
|
117
|
+
return super.buildContextPipeline().compose({
|
|
118
|
+
action: async (context) => this.initiateDownload(context),
|
|
119
|
+
cleanup: async (context) => {
|
|
120
|
+
if (!context.response.bodyUsed) {
|
|
121
|
+
// Nobody consumed the body — cancel it so the
|
|
122
|
+
// underlying connection can be released.
|
|
123
|
+
await context.response.body?.cancel();
|
|
124
|
+
}
|
|
125
|
+
await context[kBodyDrained];
|
|
126
|
+
},
|
|
118
127
|
});
|
|
119
128
|
}
|
|
120
129
|
async initiateDownload(context) {
|
|
121
|
-
const response = await this.httpClient.
|
|
122
|
-
|
|
123
|
-
timeout: { request: undefined },
|
|
124
|
-
proxyUrl: context.proxyInfo?.url,
|
|
130
|
+
const response = await this.httpClient.sendRequest(context.request.intoFetchAPIRequest(), {
|
|
131
|
+
session: context.session,
|
|
125
132
|
});
|
|
126
133
|
const { type, charset: encoding } = parseContentTypeFromResponse(response);
|
|
127
134
|
context.request.url = response.url;
|
|
135
|
+
const { response: trackedResponse, bodyDrained } = trackBodyConsumption(response);
|
|
128
136
|
const contextExtension = {
|
|
129
137
|
request: context.request,
|
|
130
|
-
response,
|
|
138
|
+
response: trackedResponse,
|
|
131
139
|
contentType: { type, encoding },
|
|
140
|
+
[kBodyDrained]: bodyDrained,
|
|
132
141
|
};
|
|
133
142
|
return contextExtension;
|
|
134
143
|
}
|
|
135
144
|
}
|
|
136
145
|
/**
|
|
137
|
-
*
|
|
138
|
-
*
|
|
139
|
-
*
|
|
140
|
-
*
|
|
141
|
-
* > Serves as a shortcut for using `Router.create<FileDownloadCrawlingContext>()`.
|
|
142
|
-
*
|
|
143
|
-
* ```ts
|
|
144
|
-
* import { FileDownload, createFileRouter } from 'crawlee';
|
|
145
|
-
*
|
|
146
|
-
* const router = createFileRouter();
|
|
147
|
-
* router.addHandler('label-a', async (ctx) => {
|
|
148
|
-
* ctx.log.info('...');
|
|
149
|
-
* });
|
|
150
|
-
* router.addDefaultHandler(async (ctx) => {
|
|
151
|
-
* ctx.log.info('...');
|
|
152
|
-
* });
|
|
153
|
-
*
|
|
154
|
-
* const crawler = new FileDownload({
|
|
155
|
-
* requestHandler: router,
|
|
156
|
-
* });
|
|
157
|
-
* await crawler.run();
|
|
158
|
-
* ```
|
|
146
|
+
* Wraps a Response so that we can track when the body stream has been fully
|
|
147
|
+
* consumed (or errored). Pipes the original body through a TransformStream;
|
|
148
|
+
* the readable side becomes the new Response body, and `pipeTo` gives us a
|
|
149
|
+
* promise that resolves once the body is fully read or cancelled.
|
|
159
150
|
*/
|
|
160
|
-
|
|
161
|
-
|
|
151
|
+
function trackBodyConsumption(response) {
|
|
152
|
+
if (!response.body) {
|
|
153
|
+
return { response, bodyDrained: Promise.resolve() };
|
|
154
|
+
}
|
|
155
|
+
const passthrough = new TransformStream();
|
|
156
|
+
const bodyDrained = response.body.pipeTo(passthrough.writable).catch(() => { });
|
|
157
|
+
const trackedResponse = new ResponseWithUrl(passthrough.readable, {
|
|
158
|
+
headers: response.headers,
|
|
159
|
+
status: response.status,
|
|
160
|
+
statusText: response.statusText,
|
|
161
|
+
url: response.url,
|
|
162
|
+
});
|
|
163
|
+
return { response: trackedResponse, bodyDrained };
|
|
164
|
+
}
|
|
165
|
+
export function createFileRouter(routesOrSchemas) {
|
|
166
|
+
return Router.create(routesOrSchemas);
|
|
162
167
|
}
|
|
163
|
-
//# sourceMappingURL=file-download.js.map
|