@crawlee/puppeteer 3.0.0-alpha.2 → 3.0.0-alpha.3

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.
Files changed (38) hide show
  1. package/dist/LICENSE.md +201 -0
  2. package/{README.md → dist/README.md} +0 -0
  3. package/dist/index.d.ts +12 -0
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/index.js +12 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/index.mjs +76 -0
  8. package/dist/internals/enqueue-links/click-elements.d.ts +188 -0
  9. package/dist/internals/enqueue-links/click-elements.d.ts.map +1 -0
  10. package/dist/internals/enqueue-links/click-elements.js +336 -0
  11. package/dist/internals/enqueue-links/click-elements.js.map +1 -0
  12. package/dist/internals/puppeteer-crawler.d.ts +149 -0
  13. package/dist/internals/puppeteer-crawler.d.ts.map +1 -0
  14. package/dist/internals/puppeteer-crawler.js +117 -0
  15. package/dist/internals/puppeteer-crawler.js.map +1 -0
  16. package/dist/internals/puppeteer-launcher.d.ts +134 -0
  17. package/dist/internals/puppeteer-launcher.d.ts.map +1 -0
  18. package/dist/internals/puppeteer-launcher.js +146 -0
  19. package/dist/internals/puppeteer-launcher.js.map +1 -0
  20. package/dist/internals/stealth/hiding_tricks.d.ts +10 -0
  21. package/dist/internals/stealth/hiding_tricks.d.ts.map +1 -0
  22. package/dist/internals/stealth/hiding_tricks.js +334 -0
  23. package/dist/internals/stealth/hiding_tricks.js.map +1 -0
  24. package/dist/internals/stealth/index.d.ts +40 -0
  25. package/dist/internals/stealth/index.d.ts.map +1 -0
  26. package/dist/internals/stealth/index.js +108 -0
  27. package/dist/internals/stealth/index.js.map +1 -0
  28. package/dist/internals/utils/puppeteer_request_interception.d.ts +60 -0
  29. package/dist/internals/utils/puppeteer_request_interception.d.ts.map +1 -0
  30. package/dist/internals/utils/puppeteer_request_interception.js +225 -0
  31. package/dist/internals/utils/puppeteer_request_interception.js.map +1 -0
  32. package/dist/internals/utils/puppeteer_utils.d.ts +298 -0
  33. package/dist/internals/utils/puppeteer_utils.d.ts.map +1 -0
  34. package/dist/internals/utils/puppeteer_utils.js +468 -0
  35. package/dist/internals/utils/puppeteer_utils.js.map +1 -0
  36. package/dist/package.json +66 -0
  37. package/dist/tsconfig.build.tsbuildinfo +1 -0
  38. package/package.json +8 -7
@@ -0,0 +1,298 @@
1
+ /**
2
+ * A namespace that contains various utilities for
3
+ * [Puppeteer](https://github.com/puppeteer/puppeteer) - the headless Chrome Node API.
4
+ *
5
+ * **Example usage:**
6
+ *
7
+ * ```javascript
8
+ * const Apify = require('apify');
9
+ * const { puppeteer } = Actor.utils;
10
+ *
11
+ * // Open https://www.example.com in Puppeteer
12
+ * const browser = await Actor.launchPuppeteer();
13
+ * const page = await browser.newPage();
14
+ * await page.goto('https://www.example.com');
15
+ *
16
+ * // Inject jQuery into a page
17
+ * await puppeteer.injectJQuery(page);
18
+ * ```
19
+ * @module puppeteerUtils
20
+ */
21
+ import { Page, HTTPResponse, ResponseForRequest } from 'puppeteer';
22
+ import { Request } from '@crawlee/core';
23
+ import { Dictionary } from '@crawlee/utils';
24
+ import { enqueueLinksByClickingElements } from '../enqueue-links/click-elements';
25
+ import { addInterceptRequestHandler, removeInterceptRequestHandler } from './puppeteer_request_interception';
26
+ export interface DirectNavigationOptions {
27
+ /**
28
+ * Maximum operation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The
29
+ * default value can be changed by using the browserContext.setDefaultNavigationTimeout(timeout),
30
+ * browserContext.setDefaultTimeout(timeout), page.setDefaultNavigationTimeout(timeout) or
31
+ * page.setDefaultTimeout(timeout) methods.
32
+ */
33
+ timeout?: number;
34
+ /**
35
+ * When to consider operation succeeded, defaults to `load`. Events can be either:
36
+ * - `'domcontentloaded'` - consider operation to be finished when the `DOMContentLoaded` event is fired.
37
+ * - `'load'` - consider operation to be finished when the `load` event is fired.
38
+ * - `'networkidle'` - consider operation to be finished when there are no network connections for at least `500` ms.
39
+ */
40
+ waitUntil?: 'domcontentloaded' | 'load' | 'networkidle';
41
+ /**
42
+ * Referer header value. If provided it will take preference over the referer header value set by page.setExtraHTTPHeaders(headers).
43
+ */
44
+ referer?: string;
45
+ }
46
+ export interface InjectFileOptions {
47
+ /**
48
+ * Enables the injected script to survive page navigations and reloads without need to be re-injected manually.
49
+ * This does not mean, however, that internal state will be preserved. Just that it will be automatically
50
+ * re-injected on each navigation before any other scripts get the chance to execute.
51
+ */
52
+ surviveNavigations?: boolean;
53
+ }
54
+ export interface BlockRequestsOptions {
55
+ /**
56
+ * The patterns of URLs to block from being loaded by the browser.
57
+ * Only `*` can be used as a wildcard. It is also automatically added to the beginning
58
+ * and end of the pattern. This limitation is enforced by the DevTools protocol.
59
+ * `.png` is the same as `*.png*`.
60
+ */
61
+ urlPatterns?: string[];
62
+ /**
63
+ * If you just want to append to the default blocked patterns, use this property.
64
+ */
65
+ extraUrlPatterns?: string[];
66
+ }
67
+ export interface CompiledScriptParams {
68
+ page: Page;
69
+ request: Request;
70
+ }
71
+ export declare type CompiledScriptFunction = (params: CompiledScriptParams) => Promise<unknown>;
72
+ /**
73
+ * Injects a JavaScript file into a Puppeteer page.
74
+ * Unlike Puppeteer's `addScriptTag` function, this function works on pages
75
+ * with arbitrary Cross-Origin Resource Sharing (CORS) policies.
76
+ *
77
+ * File contents are cached for up to 10 files to limit file system access.
78
+ *
79
+ * @param page Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.
80
+ * @param filePath File path
81
+ * @param [options]
82
+ */
83
+ export declare function injectFile(page: Page, filePath: string, options?: InjectFileOptions): Promise<unknown>;
84
+ /**
85
+ * Injects the [jQuery](https://jquery.com/) library into a Puppeteer page.
86
+ * jQuery is often useful for various web scraping and crawling tasks.
87
+ * For example, it can help extract text from HTML elements using CSS selectors.
88
+ *
89
+ * Beware that the injected jQuery object will be set to the `window.$` variable and thus it might cause conflicts with
90
+ * other libraries included by the page that use the same variable name (e.g. another version of jQuery).
91
+ * This can affect functionality of page's scripts.
92
+ *
93
+ * The injected jQuery will survive page navigations and reloads.
94
+ *
95
+ * **Example usage:**
96
+ * ```javascript
97
+ * await Actor.utils.puppeteer.injectJQuery(page);
98
+ * const title = await page.evaluate(() => {
99
+ * return $('head title').text();
100
+ * });
101
+ * ```
102
+ *
103
+ * Note that `injectJQuery()` does not affect the Puppeteer's
104
+ * [`page.$()`](https://pptr.dev/#?product=Puppeteer&show=api-pageselector)
105
+ * function in any way.
106
+ *
107
+ * @param page Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.
108
+ */
109
+ export declare function injectJQuery(page: Page): Promise<unknown>;
110
+ /**
111
+ * Forces the Puppeteer browser tab to block loading URLs that match a provided pattern.
112
+ * This is useful to speed up crawling of websites, since it reduces the amount
113
+ * of data that needs to be downloaded from the web, but it may break some websites
114
+ * or unexpectedly prevent loading of resources.
115
+ *
116
+ * By default, the function will block all URLs including the following patterns:
117
+ *
118
+ * ```json
119
+ * [".css", ".jpg", ".jpeg", ".png", ".svg", ".gif", ".woff", ".pdf", ".zip"]
120
+ * ```
121
+ *
122
+ * If you want to extend this list further, use the `extraUrlPatterns` option,
123
+ * which will keep blocking the default patterns, as well as add your custom ones.
124
+ * If you would like to block only specific patterns, use the `urlPatterns` option,
125
+ * which will override the defaults and block only URLs with your custom patterns.
126
+ *
127
+ * This function does not use Puppeteer's request interception and therefore does not interfere
128
+ * with browser cache. It's also faster than blocking requests using interception,
129
+ * because the blocking happens directly in the browser without the round-trip to Node.js,
130
+ * but it does not provide the extra benefits of request interception.
131
+ *
132
+ * The function will never block main document loads and their respective redirects.
133
+ *
134
+ * **Example usage**
135
+ * ```javascript
136
+ * const Apify = require('apify');
137
+ *
138
+ * const browser = await Actor.launchPuppeteer();
139
+ * const page = await browser.newPage();
140
+ *
141
+ * // Block all requests to URLs that include `adsbygoogle.js` and also all defaults.
142
+ * await Actor.utils.puppeteer.blockRequests(page, {
143
+ * extraUrlPatterns: ['adsbygoogle.js'],
144
+ * });
145
+ *
146
+ * await page.goto('https://cnn.com');
147
+ * ```
148
+ *
149
+ * @param page Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.
150
+ * @param [options]
151
+ */
152
+ export declare function blockRequests(page: Page, options?: BlockRequestsOptions): Promise<void>;
153
+ /**
154
+ * `blockResources()` has a high impact on performance in recent versions of Puppeteer.
155
+ * Until this resolves, please use `Actor.utils.puppeteer.blockRequests()`.
156
+ * @deprecated
157
+ */
158
+ export declare const blockResources: (page: Page, resourceTypes?: string[]) => Promise<void>;
159
+ /**
160
+ * *NOTE:* In recent versions of Puppeteer using this function entirely disables browser cache which resolves in sub-optimal
161
+ * performance. Until this resolves, we suggest just relying on the in-browser cache unless absolutely necessary.
162
+ *
163
+ * Enables caching of intercepted responses into a provided object. Automatically enables request interception in Puppeteer.
164
+ * *IMPORTANT*: Caching responses stores them to memory, so too loose rules could cause memory leaks for longer running crawlers.
165
+ * This issue should be resolved or atleast mitigated in future iterations of this feature.
166
+ * @param page
167
+ * Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.
168
+ * @param cache
169
+ * Object in which responses are stored
170
+ * @param responseUrlRules
171
+ * List of rules that are used to check if the response should be cached.
172
+ * String rules are compared as page.url().includes(rule) while RegExp rules are evaluated as rule.test(page.url()).
173
+ * @deprecated
174
+ */
175
+ export declare function cacheResponses(page: Page, cache: Dictionary<Partial<ResponseForRequest>>, responseUrlRules: (string | RegExp)[]): Promise<void>;
176
+ /**
177
+ * Compiles a Puppeteer script into an async function that may be executed at any time
178
+ * by providing it with the following object:
179
+ * ```
180
+ * {
181
+ * page: Page,
182
+ * request: Request,
183
+ * }
184
+ * ```
185
+ * Where `page` is a Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page)
186
+ * and `request` is a {@link Request}.
187
+ *
188
+ * The function is compiled by using the `scriptString` parameter as the function's body,
189
+ * so any limitations to function bodies apply. Return value of the compiled function
190
+ * is the return value of the function body = the `scriptString` parameter.
191
+ *
192
+ * As a security measure, no globals such as `process` or `require` are accessible
193
+ * from within the function body. Note that the function does not provide a safe
194
+ * sandbox and even though globals are not easily accessible, malicious code may
195
+ * still execute in the main process via prototype manipulation. Therefore you
196
+ * should only use this function to execute sanitized or safe code.
197
+ *
198
+ * Custom context may also be provided using the `context` parameter. To improve security,
199
+ * make sure to only pass the really necessary objects to the context. Preferably making
200
+ * secured copies beforehand.
201
+ *
202
+ */
203
+ export declare function compileScript(scriptString: string, context?: Dictionary): CompiledScriptFunction;
204
+ /**
205
+ * Extended version of Puppeteer's `page.goto()` allowing to perform requests with HTTP method other than GET,
206
+ * with custom headers and POST payload. URL, method, headers and payload are taken from
207
+ * request parameter that must be an instance of Request class.
208
+ *
209
+ * *NOTE:* In recent versions of Puppeteer using requests other than GET, overriding headers and adding payloads disables
210
+ * browser cache which degrades performance.
211
+ *
212
+ * @param page Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.
213
+ * @param request
214
+ * @param [gotoOptions] Custom options for `page.goto()`.
215
+ */
216
+ export declare function gotoExtended(page: Page, request: Request, gotoOptions?: DirectNavigationOptions): Promise<HTTPResponse | null>;
217
+ export interface InfiniteScrollOptions {
218
+ /**
219
+ * How many seconds to scroll for. If 0, will scroll until bottom of page.
220
+ * @default 1
221
+ */
222
+ timeoutSecs?: number;
223
+ /**
224
+ * How many seconds to wait for no new content to load before exit.
225
+ * @default 4
226
+ */
227
+ waitForSecs?: number;
228
+ /**
229
+ * If true, it will scroll up a bit after each scroll down. This is required on some websites for the scroll to work.
230
+ * @default false
231
+ */
232
+ scrollDownAndUp?: boolean;
233
+ /**
234
+ * Optionally checks and clicks a button if it appears while scrolling. This is required on some websites for the scroll to work.
235
+ */
236
+ buttonSelector?: string;
237
+ /**
238
+ * This function is called after every scroll and stops the scrolling process if it returns `true`. The function can be `async`.
239
+ */
240
+ stopScrollCallback?: () => unknown | Promise<unknown>;
241
+ }
242
+ /**
243
+ * Scrolls to the bottom of a page, or until it times out.
244
+ * Loads dynamic content when it hits the bottom of a page, and then continues scrolling.
245
+ * @param page Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.
246
+ * @param [options]
247
+ */
248
+ export declare function infiniteScroll(page: Page, options?: InfiniteScrollOptions): Promise<void>;
249
+ export interface SaveSnapshotOptions {
250
+ /**
251
+ * Key under which the screenshot and HTML will be saved. `.jpg` will be appended for screenshot and `.html` for HTML.
252
+ * @default 'SNAPSHOT'
253
+ */
254
+ key?: string;
255
+ /**
256
+ * The quality of the image, between 0-100. Higher quality images have bigger size and require more storage.
257
+ * @default 50
258
+ */
259
+ screenshotQuality?: number;
260
+ /**
261
+ * If true, it will save a full screenshot of the current page as a record with `key` appended by `.jpg`.
262
+ * @default true
263
+ */
264
+ saveScreenshot?: boolean;
265
+ /**
266
+ * If true, it will save a full HTML of the current page as a record with `key` appended by `.html`.
267
+ * @default true
268
+ */
269
+ saveHtml?: boolean;
270
+ /**
271
+ * Name or id of the Key-Value store where snapshot is saved. By default it is saved to default Key-Value store.
272
+ * @default null
273
+ */
274
+ keyValueStoreName?: string | null;
275
+ }
276
+ /**
277
+ * Saves a full screenshot and HTML of the current page into a Key-Value store.
278
+ * @param page Puppeteer [`Page`](https://pptr.dev/#?product=Puppeteer&show=api-class-page) object.
279
+ * @param [options]
280
+ */
281
+ export declare function saveSnapshot(page: Page, options?: SaveSnapshotOptions): Promise<void>;
282
+ export { enqueueLinksByClickingElements, addInterceptRequestHandler, removeInterceptRequestHandler, };
283
+ /** @internal */
284
+ export declare const puppeteerUtils: {
285
+ injectFile: typeof injectFile;
286
+ injectJQuery: typeof injectJQuery;
287
+ enqueueLinksByClickingElements: typeof enqueueLinksByClickingElements;
288
+ blockRequests: typeof blockRequests;
289
+ blockResources: (page: Page, resourceTypes?: string[]) => Promise<void>;
290
+ cacheResponses: typeof cacheResponses;
291
+ compileScript: typeof compileScript;
292
+ gotoExtended: typeof gotoExtended;
293
+ addInterceptRequestHandler: typeof addInterceptRequestHandler;
294
+ removeInterceptRequestHandler: typeof removeInterceptRequestHandler;
295
+ infiniteScroll: typeof infiniteScroll;
296
+ saveSnapshot: typeof saveSnapshot;
297
+ };
298
+ //# sourceMappingURL=puppeteer_utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"puppeteer_utils.d.ts","sourceRoot":"","sources":["../../../src/internals/utils/puppeteer_utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAOH,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,kBAAkB,EAAmC,MAAM,WAAW,CAAC;AAEpG,OAAO,EAAiB,OAAO,EAAc,MAAM,eAAe,CAAC;AACnE,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,8BAA8B,EAAE,MAAM,iCAAiC,CAAC;AACjF,OAAO,EAAE,0BAA0B,EAAE,6BAA6B,EAAE,MAAM,kCAAkC,CAAC;AAU7G,MAAM,WAAW,uBAAuB;IACpC;;;;;OAKG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB;;;;;OAKG;IACH,SAAS,CAAC,EAAE,kBAAkB,GAAG,MAAM,GAAG,aAAa,CAAC;IAExD;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,iBAAiB;IAC9B;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAChC;AAED,MAAM,WAAW,oBAAoB;IACjC;;;;;OAKG;IACH,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;IAEvB;;OAEG;IACH,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;CAC/B;AAED,MAAM,WAAW,oBAAoB;IACjC,IAAI,EAAE,IAAI,CAAC;IACX,OAAO,EAAE,OAAO,CAAC;CACpB;AAED,oBAAY,sBAAsB,GAAG,CAAC,MAAM,EAAE,oBAAoB,KAAK,OAAO,CAAC,OAAO,CAAC,CAA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