Skip to content

Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.

Format Markdown with Prettier

David Turnbullb43959c31aad
diff --git a/docs/api/Apify.md b/docs/api/Apify.md
index e6988c1e8..efcc6eaaa 100644
--- a/docs/api/Apify.md
+++ b/docs/api/Apify.md
@@ -2,38 +2,39 @@
id: apify
title: Apify
---
+
<a name="module_Apify"></a>
The following section describes all functions and properties provided by the `apify` package,
except individual classes and namespaces that have their separate, detailed, documentation pages
accessible from the left sidebar.
-
-* [Apify](#module_Apify)
- * [`.addWebhook(options)`](#module_Apify.addWebhook) ⇒ `Promise<Object>`
- * [`.call(actId, [input], [options])`](#module_Apify.call) ⇒ [`Promise<ActorRun>`](../typedefs/actorrun)
- * [`.callTask(taskId, [input], [options])`](#module_Apify.callTask) ⇒ [`Promise<ActorRun>`](../typedefs/actorrun)
- * [`.client`](#module_Apify.client)
- * [`.events`](#module_Apify.events)
- * [`.getApifyProxyUrl(options)`](#module_Apify.getApifyProxyUrl) ⇒ `String`
- * [`.getEnv()`](#module_Apify.getEnv) ⇒ `Object`
- * [`.getInput`](#module_Apify.getInput) ⇒ `Promise<Object>`
- * [`.getMemoryInfo()`](#module_Apify.getMemoryInfo) ⇒ `Promise<Object>`
- * [`.getValue(key)`](#module_Apify.getValue) ⇒ `Promise<Object>`
- * [`.isAtHome()`](#module_Apify.isAtHome) ⇒ `Boolean`
- * [`.launchPuppeteer([options])`](#module_Apify.launchPuppeteer) ⇒ `Promise<Browser>`
- * [`.main(userFunc)`](#module_Apify.main)
- * [`.metamorph(targetActorId, [input], [options])`](#module_Apify.metamorph) ⇒ `Promise`
- * [`.openDataset([datasetIdOrName], [options])`](#module_Apify.openDataset) ⇒ [`Promise<Dataset>`](dataset)
- * [`.openKeyValueStore([storeIdOrName], [options])`](#module_Apify.openKeyValueStore) ⇒ [`Promise<KeyValueStore>`](keyvaluestore)
- * [`.openRequestList`](#module_Apify.openRequestList) ⇒ [`Promise<RequestList>`](requestlist)
- * [`.openRequestQueue`](#module_Apify.openRequestQueue) ⇒ [`Promise<RequestQueue>`](requestqueue)
- * [`.pushData(item)`](#module_Apify.pushData) ⇒ `Promise`
- * [`.setValue(key, value, [options])`](#module_Apify.setValue) ⇒ `Promise`
+- [Apify](#module_Apify)
+ - [`.addWebhook(options)`](#module_Apify.addWebhook) ⇒ `Promise<Object>`
+ - [`.call(actId, [input], [options])`](#module_Apify.call) ⇒ [`Promise<ActorRun>`](../typedefs/actorrun)
+ - [`.callTask(taskId, [input], [options])`](#module_Apify.callTask) ⇒ [`Promise<ActorRun>`](../typedefs/actorrun)
+ - [`.client`](#module_Apify.client)
+ - [`.events`](#module_Apify.events)
+ - [`.getApifyProxyUrl(options)`](#module_Apify.getApifyProxyUrl) ⇒ `String`
+ - [`.getEnv()`](#module_Apify.getEnv) ⇒ `Object`
+ - [`.getInput`](#module_Apify.getInput) ⇒ `Promise<Object>`
+ - [`.getMemoryInfo()`](#module_Apify.getMemoryInfo) ⇒ `Promise<Object>`
+ - [`.getValue(key)`](#module_Apify.getValue) ⇒ `Promise<Object>`
+ - [`.isAtHome()`](#module_Apify.isAtHome) ⇒ `Boolean`
+ - [`.launchPuppeteer([options])`](#module_Apify.launchPuppeteer) ⇒ `Promise<Browser>`
+ - [`.main(userFunc)`](#module_Apify.main)
+ - [`.metamorph(targetActorId, [input], [options])`](#module_Apify.metamorph) ⇒ `Promise`
+ - [`.openDataset([datasetIdOrName], [options])`](#module_Apify.openDataset) ⇒ [`Promise<Dataset>`](dataset)
+ - [`.openKeyValueStore([storeIdOrName], [options])`](#module_Apify.openKeyValueStore) ⇒ [`Promise<KeyValueStore>`](keyvaluestore)
+ - [`.openRequestList`](#module_Apify.openRequestList) ⇒ [`Promise<RequestList>`](requestlist)
+ - [`.openRequestQueue`](#module_Apify.openRequestQueue) ⇒ [`Promise<RequestQueue>`](requestqueue)
+ - [`.pushData(item)`](#module_Apify.pushData) ⇒ `Promise`
+ - [`.setValue(key, value, [options])`](#module_Apify.setValue) ⇒ `Promise`
<a name="module_Apify.addWebhook"></a>
## `Apify.addWebhook(options)` ⇒ `Promise<Object>`
+
Creates an ad-hoc webhook for the current actor run, which lets you receive a notification when the actor run finished or failed.
For more information about Apify actor webhooks, please see the <a href="https://apify.com/docs/webhooks" target="_blank">documentation</a>.
@@ -41,7 +42,8 @@ Note that webhooks are only supported for actors running on the Apify platform.
In local environment, the function will print a warning and have no effect.
**Returns**: `Promise<Object>` - The return value is the Webhook object.
-For more information, see the [Get webhook](https://apify.com/docs/api/v2#/reference/webhooks/webhook-object/get-webhook) API endpoint.
+For more information, see the [Get webhook](https://apify.com/docs/api/v2#/reference/webhooks/webhook-object/get-webhook) API endpoint.
+
<table>
<thead>
<tr>
@@ -87,6 +89,7 @@ For more information, see the [Get webhook](https://apify.com/docs/api/v2#/refer
<a name="module_Apify.call"></a>
## `Apify.call(actId, [input], [options])` ⇒ [`Promise<ActorRun>`](../typedefs/actorrun)
+
Runs an actor on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
waits for the actor to finish and fetches its output.
@@ -106,7 +109,7 @@ For more information about actors, read the
**Example usage:**
```javascript
-const run = await Apify.call('apify/hello-world', { myInput: 123 });
+const run = await Apify.call("apify/hello-world", { myInput: 123 });
console.log(`Received message: ${run.output.body.message}`);
```
@@ -116,7 +119,7 @@ and several other API endpoints to obtain the output.
**Throws**:
-- [`ApifyCallError`](../typedefs/apifycallerror) If the run did not succeed, e.g. if it failed or timed out.
+- [`ApifyCallError`](../typedefs/apifycallerror) If the run did not succeed, e.g. if it failed or timed out.
<table>
<thead>
@@ -197,6 +200,7 @@ and several other API endpoints to obtain the output.
<a name="module_Apify.callTask"></a>
## `Apify.callTask(taskId, [input], [options])` ⇒ [`Promise<ActorRun>`](../typedefs/actorrun)
+
Runs an actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
waits for the task to finish and fetches its output.
@@ -216,7 +220,7 @@ For more information about actor tasks, read the [`documentation`](https://apify
**Example usage:**
```javascript
-const run = await Apify.callTask('bob/some-task');
+const run = await Apify.callTask("bob/some-task");
console.log(`Received message: ${run.output.body.message}`);
```
@@ -226,7 +230,7 @@ and several other API endpoints to obtain the output.
**Throws**:
-- [`ApifyCallError`](../typedefs/apifycallerror) If the run did not succeed, e.g. if it failed or timed out.
+- [`ApifyCallError`](../typedefs/apifycallerror) If the run did not succeed, e.g. if it failed or timed out.
<table>
<thead>
@@ -297,6 +301,7 @@ and several other API endpoints to obtain the output.
<a name="module_Apify.client"></a>
## `Apify.client`
+
Gets the default instance of the `ApifyClient` class provided
<a href="https://apify.com/docs/sdk/apify-client-js/latest"
target="_blank">apify-client</a> by the NPM package.
@@ -313,6 +318,7 @@ Beware that altering these settings might have unintended effects on the entire
<a name="module_Apify.events"></a>
## `Apify.events`
+
Gets an instance of a Node.js'
<a href="https://nodejs.org/api/events.html#events_class_eventemitter" target="_blank">EventEmitter</a>
class that emits various events from the SDK or the Apify platform.
@@ -321,12 +327,13 @@ The event emitter is initialized by calling the [`Apify.main()`](#module_Apify.m
**Example usage:**
```javascript
-Apify.events.on('cpuInfo', (data) => {
- if (data.isCpuOverloaded) console.log('Oh no, the CPU is overloaded!');
+Apify.events.on("cpuInfo", data => {
+ if (data.isCpuOverloaded) console.log("Oh no, the CPU is overloaded!");
});
```
The following table shows all currently emitted events:
+
<table>
<thead>
<tr>
@@ -378,6 +385,7 @@ The following table shows all currently emitted events:
<a name="module_Apify.getApifyProxyUrl"></a>
## `Apify.getApifyProxyUrl(options)` ⇒ `String`
+
Constructs an Apify Proxy URL using the specified settings.
The proxy URL can be used from Apify actors, web browsers or any other HTTP
proxy-enabled applications.
@@ -386,7 +394,8 @@ For more information, see
the <a href="https://my.apify.com/proxy" target="_blank">Apify Proxy</a> page in the app
or the <a href="https://apify.com/docs/proxy" target="_blank">documentation</a>.
-**Returns**: `String` - Returns the proxy URL, e.g. `http://auto:[email protected]:8000`.
+**Returns**: `String` - Returns the proxy URL, e.g. `http://auto:[email protected]:8000`.
+
<table>
<thead>
<tr>
@@ -427,6 +436,7 @@ or the <a href="https://apify.com/docs/proxy" target="_blank">documentation</a>.
<a name="module_Apify.getEnv"></a>
## `Apify.getEnv()` ⇒ `Object`
+
Returns a new object which contains information parsed from all the `APIFY_XXX` environment variables.
It has properties such as the following:
@@ -459,6 +469,7 @@ It has properties such as the following:
memoryMbytes: Number,
}
```
+
For the list of the `APIFY_XXX` environment variables, see
<a href="https://apify.com/docs/actor#run-env-vars" target="_blank">Actor documentation</a>.
If some of the variables are not defined or are invalid, the corresponding value in the resulting object will be null.
@@ -466,18 +477,21 @@ If some of the variables are not defined or are invalid, the corresponding value
<a name="module_Apify.getInput"></a>
## `Apify.getInput` ⇒ `Promise<Object>`
+
Gets the actor input value from the default [`KeyValueStore`](keyvaluestore) associated with the current actor run.
This is just a convenient shortcut for [`keyValueStore.getValue('INPUT')`](keyvaluestore#KeyValueStore+getValue).
For example, calling the following code:
+
```javascript
const input = await Apify.getInput();
```
is equivalent to:
+
```javascript
const store = await Apify.openKeyValueStore();
-await store.getValue('INPUT');
+await store.getValue("INPUT");
```
For more information, see [`Apify.openKeyValueStore()`](#module_Apify.openKeyValueStore)
@@ -487,6 +501,7 @@ and [`keyValueStore.getValue()`](keyvaluestore#KeyValueStore+getValue).
<a name="module_Apify.getMemoryInfo"></a>
## `Apify.getMemoryInfo()` ⇒ `Promise<Object>`
+
Returns memory statistics of the process and the system, which is an object with the following properties:
```javascript
@@ -513,18 +528,21 @@ Therefore you shouldn't call it too often, like more than once per second.
<a name="module_Apify.getValue"></a>
## `Apify.getValue(key)` ⇒ `Promise<Object>`
+
Gets a value from the default [`KeyValueStore`](keyvaluestore) associated with the current actor run.
This is just a convenient shortcut for [`keyValueStore.getValue()`](keyvaluestore#KeyValueStore+getValue).
For example, calling the following code:
+
```javascript
-const input = await Apify.getValue('my-key');
+const input = await Apify.getValue("my-key");
```
is equivalent to:
+
```javascript
const store = await Apify.openKeyValueStore();
-await store.getValue('my-key');
+await store.getValue("my-key");
```
To store the value to the default-key value store, you can use the [`Apify.setValue()`](#module_Apify.setValue) function.
@@ -532,7 +550,8 @@ To store the value to the default-key value store, you can use the [`Apify.setVa
For more information, see [`Apify.openKeyValueStore()`](#module_Apify.openKeyValueStore)
and [`keyValueStore.getValue()`](keyvaluestore#KeyValueStore+getValue).
-**Returns**: `Promise<Object>` - Returns a promise that resolves once the record is stored.
+**Returns**: `Promise<Object>` - Returns a promise that resolves once the record is stored.
+
<table>
<thead>
<tr>
@@ -550,11 +569,13 @@ and [`keyValueStore.getValue()`](keyvaluestore#KeyValueStore+getValue).
<a name="module_Apify.isAtHome"></a>
## `Apify.isAtHome()` ⇒ `Boolean`
+
Returns `true` when code is running on Apify platform and `false` otherwise (for example locally).
<a name="module_Apify.launchPuppeteer"></a>
## `Apify.launchPuppeteer([options])` ⇒ `Promise<Browser>`
+
Launches headless Chrome using Puppeteer pre-configured to work within the Apify platform.
The function has the same argument and the return value as `puppeteer.launch()`.
See <a href="https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#puppeteerlaunchoptions" target="_blank">
@@ -602,7 +623,8 @@ for details.
For an example of usage, see the [Synchronous run Example](../examples/synchronousrun)
or the [Puppeteer proxy Example](../examples/puppeteerwithproxy)
-**Returns**: `Promise<Browser>` - Promise that resolves to Puppeteer's `Browser` instance.
+**Returns**: `Promise<Browser>` - Promise that resolves to Puppeteer's `Browser` instance.
+
<table>
<thead>
<tr>
@@ -622,6 +644,7 @@ or the [Puppeteer proxy Example](../examples/puppeteerwithproxy)
<a name="module_Apify.main"></a>
## `Apify.main(userFunc)`
+
Runs the main user function that performs the job of the actor.
`Apify.main()` is especially useful when you're running your code in an actor on the Apify platform.
@@ -650,32 +673,33 @@ The user function can be synchronous:
```javascript
Apify.main(() => {
- // My synchronous function that returns immediately
- console.log('Hello world from actor!');
+ // My synchronous function that returns immediately
+ console.log("Hello world from actor!");
});
```
If the user function returns a promise, it is considered asynchronous:
+
```javascript
-const request = require('request-promise-native');
+const request = require("request-promise-native");
Apify.main(() => {
- // My asynchronous function that returns a promise
- return request('http://www.example.com').then((html) => {
- console.log(html);
- });
+ // My asynchronous function that returns a promise
+ return request("http://www.example.com").then(html => {
+ console.log(html);
+ });
});
```
To simplify your code, you can take advantage of the `async`/`await` keywords:
```javascript
-const request = require('request-promise-native');
+const request = require("request-promise-native");
Apify.main(async () => {
- // My asynchronous function
- const html = await request('http://www.example.com');
- console.log(html);
+ // My asynchronous function
+ const html = await request("http://www.example.com");
+ console.log(html);
});
```
@@ -697,6 +721,7 @@ the promise will be awaited. The user function is called with no arguments.</p>
<a name="module_Apify.metamorph"></a>
## `Apify.metamorph(targetActorId, [input], [options])` ⇒ `Promise`
+
Transforms this actor run to an actor run of a given actor. The system stops the current container and starts the new container
instead. All the default storages are preserved and the new input is stored under the `INPUT-METAMORPH-1` key in the same default key-value store.
@@ -743,6 +768,7 @@ instead. All the default storages are preserved and the new input is stored unde
<a name="module_Apify.openDataset"></a>
## `Apify.openDataset([datasetIdOrName], [options])` ⇒ [`Promise<Dataset>`](dataset)
+
Opens a dataset and returns a promise resolving to an instance of the [`Dataset`](dataset) class.
Datasets are used to store structured data where each object stored has the same attributes,
@@ -779,6 +805,7 @@ For more details and code examples, see the [`Dataset`](dataset) class.
<a name="module_Apify.openKeyValueStore"></a>
## `Apify.openKeyValueStore([storeIdOrName], [options])` ⇒ [`Promise<KeyValueStore>`](keyvaluestore)
+
Opens a key-value store and returns a promise resolving to an instance of the [`KeyValueStore`](keyvaluestore) class.
Key-value stores are used to store records or files, along with their MIME content type.
@@ -815,6 +842,7 @@ For more details and code examples, see the [`KeyValueStore`](keyvaluestore) cla
<a name="module_Apify.openRequestList"></a>
## `Apify.openRequestList` ⇒ [`Promise<RequestList>`](requestlist)
+
Opens a request list and returns a promise resolving to an instance
of the [`RequestList`](requestlist) class that is already initialized.
@@ -829,12 +857,12 @@ For more details and code examples, see the [`RequestList`](requestlist) class.
```javascript
const sources = [
- 'https://www.example.com',
- 'https://www.google.com',
- 'https://www.bing.com'
+ "https://www.example.com",
+ "https://www.google.com",
+ "https://www.bing.com"
];
-const requestList = await Apify.openRequestList('my-name', sources);
+const requestList = await Apify.openRequestList("my-name", sources);
```
<table>
@@ -879,6 +907,7 @@ const requestList = await Apify.openRequestList('my-name', sources);
<a name="module_Apify.openRequestQueue"></a>
## `Apify.openRequestQueue` ⇒ [`Promise<RequestQueue>`](requestqueue)
+
Opens a request queue and returns a promise resolving to an instance
of the [`RequestQueue`](requestqueue) class.
@@ -917,15 +946,18 @@ For more details and code examples, see the [`RequestQueue`](requestqueue) class
<a name="module_Apify.pushData"></a>
## `Apify.pushData(item)` ⇒ `Promise`
+
Stores an object or an array of objects to the default [`Dataset`](dataset) of the current actor run.
This is just a convenient shortcut for [`dataset.pushData()`](dataset#Dataset+pushData).
For example, calling the following code:
+
```javascript
await Apify.pushData({ myValue: 123 });
```
is equivalent to:
+
```javascript
const dataset = await Apify.openDataset();
await dataset.pushData({ myValue: 123 });
@@ -954,18 +986,21 @@ The objects must be serializable to JSON and the JSON representation of each obj
<a name="module_Apify.setValue"></a>
## `Apify.setValue(key, value, [options])` ⇒ `Promise`
+
Stores or deletes a value in the default [`KeyValueStore`](keyvaluestore) associated with the current actor run.
This is just a convenient shortcut for [`keyValueStore.setValue()`](keyvaluestore#KeyValueStore+setValue).
For example, calling the following code:
+
```javascript
-await Apify.setValue('OUTPUT', { foo: "bar" });
+await Apify.setValue("OUTPUT", { foo: "bar" });
```
is equivalent to:
+
```javascript
const store = await Apify.openKeyValueStore();
-await store.setValue('OUTPUT', { foo: "bar" });
+await store.setValue("OUTPUT", { foo: "bar" });
```
To get a value from the default-key value store, you can use the [`Apify.getValue()`](#module_Apify.getValue) function.
diff --git a/docs/api/AutoscaledPool.md b/docs/api/AutoscaledPool.md
index 981d13c63..151979f80 100644
--- a/docs/api/AutoscaledPool.md
+++ b/docs/api/AutoscaledPool.md
@@ -2,6 +2,7 @@
id: autoscaledpool
title: AutoscaledPool
---
+
<a name="AutoscaledPool"></a>
Manages a pool of asynchronous resource-intensive tasks that are executed in parallel.
@@ -50,24 +51,24 @@ const pool = new Apify.AutoscaledPool({
await pool.run();
```
-
-* [AutoscaledPool](autoscaledpool)
- * [`new AutoscaledPool(options)`](#new_AutoscaledPool_new)
- * [`.minConcurrency`](#AutoscaledPool+minConcurrency) ⇒ `number`
- * [`.minConcurrency`](#AutoscaledPool+minConcurrency)
- * [`.maxConcurrency`](#AutoscaledPool+maxConcurrency) ⇒ `number`
- * [`.maxConcurrency`](#AutoscaledPool+maxConcurrency)
- * [`.desiredConcurrency`](#AutoscaledPool+desiredConcurrency) ⇒ `number`
- * [`.desiredConcurrency`](#AutoscaledPool+desiredConcurrency)
- * [`.currentConcurrency`](#AutoscaledPool+currentConcurrency) ⇒ `number`
- * [`.run()`](#AutoscaledPool+run) ⇒ `Promise`
- * [`.abort()`](#AutoscaledPool+abort) ⇒ `Promise`
- * [`.pause([timeoutSecs])`](#AutoscaledPool+pause) ⇒ `Promise`
- * [`.resume()`](#AutoscaledPool+resume)
+- [AutoscaledPool](autoscaledpool)
+ - [`new AutoscaledPool(options)`](#new_AutoscaledPool_new)
+ - [`.minConcurrency`](#AutoscaledPool+minConcurrency) ⇒ `number`
+ - [`.minConcurrency`](#AutoscaledPool+minConcurrency)
+ - [`.maxConcurrency`](#AutoscaledPool+maxConcurrency) ⇒ `number`
+ - [`.maxConcurrency`](#AutoscaledPool+maxConcurrency)
+ - [`.desiredConcurrency`](#AutoscaledPool+desiredConcurrency) ⇒ `number`
+ - [`.desiredConcurrency`](#AutoscaledPool+desiredConcurrency)
+ - [`.currentConcurrency`](#AutoscaledPool+currentConcurrency) ⇒ `number`
+ - [`.run()`](#AutoscaledPool+run) ⇒ `Promise`
+ - [`.abort()`](#AutoscaledPool+abort) ⇒ `Promise`
+ - [`.pause([timeoutSecs])`](#AutoscaledPool+pause) ⇒ `Promise`
+ - [`.resume()`](#AutoscaledPool+resume)
<a name="new_AutoscaledPool_new"></a>
## `new AutoscaledPool(options)`
+
<table>
<thead>
<tr>
@@ -170,14 +171,16 @@ await pool.run();
<a name="AutoscaledPool+minConcurrency"></a>
## `autoscaledPool.minConcurrency` ⇒ `number`
+
Gets the minimum number of tasks running in parallel.
<a name="AutoscaledPool+minConcurrency"></a>
## `autoscaledPool.minConcurrency`
+
Sets the minimum number of tasks running in parallel.
-*WARNING:* If you set this value too high with respect to the available system memory and CPU, your code might run extremely slow or crash.
+_WARNING:_ If you set this value too high with respect to the available system memory and CPU, your code might run extremely slow or crash.
If you're not sure, just keep the default value and the concurrency will scale up automatically.
<table>
@@ -196,11 +199,13 @@ If you're not sure, just keep the default value and the concurrency will scale u
<a name="AutoscaledPool+maxConcurrency"></a>
## `autoscaledPool.maxConcurrency` ⇒ `number`
+
Gets the maximum number of tasks running in parallel.
<a name="AutoscaledPool+maxConcurrency"></a>
## `autoscaledPool.maxConcurrency`
+
Sets the maximum number of tasks running in parallel.
<table>
@@ -219,12 +224,14 @@ Sets the maximum number of tasks running in parallel.
<a name="AutoscaledPool+desiredConcurrency"></a>
## `autoscaledPool.desiredConcurrency` ⇒ `number`
+
Gets the desired concurrency for the pool,
which is an estimated number of parallel tasks that the system can currently support.
<a name="AutoscaledPool+desiredConcurrency"></a>
## `autoscaledPool.desiredConcurrency`
+
Sets the desired concurrency for the pool, i.e. the number of tasks that should be running
in parallel if there's large enough supply of tasks.
@@ -244,17 +251,20 @@ in parallel if there's large enough supply of tasks.
<a name="AutoscaledPool+currentConcurrency"></a>
## `autoscaledPool.currentConcurrency` ⇒ `number`
+
Gets the the number of parallel tasks currently running in the pool.
<a name="AutoscaledPool+run"></a>
## `autoscaledPool.run()` ⇒ `Promise`
+
Runs the auto-scaled pool. Returns a promise that gets resolved or rejected once
all the tasks are finished or one of them fails.
<a name="AutoscaledPool+abort"></a>
## `autoscaledPool.abort()` ⇒ `Promise`
+
Aborts the run of the auto-scaled pool and destroys it. The promise returned from
the [`run()`](#AutoscaledPool+run) function will immediately resolve, no more new tasks
will be spawned and all running tasks will be left in their current state.
@@ -268,6 +278,7 @@ parts of their asynchronous chains of commands will not execute.
<a name="AutoscaledPool+pause"></a>
## `autoscaledPool.pause([timeoutSecs])` ⇒ `Promise`
+
Prevents the auto-scaled pool from starting new tasks, but allows the running ones to finish
(unlike abort, which terminates them). Used together with [`resume()`](#AutoscaledPool+resume)
@@ -294,8 +305,8 @@ when `.pause()` is invoked (unlike abort, which resolves it).
<a name="AutoscaledPool+resume"></a>
## `autoscaledPool.resume()`
+
Resumes the operation of the autoscaled-pool by allowing more tasks to be run.
Used together with [`pause()`](#AutoscaledPool+pause)
Tasks will automatically start running again in `options.maybeRunIntervalSecs`.
-
diff --git a/docs/api/BasicCrawler.md b/docs/api/BasicCrawler.md
index f2bd8b697..708ea6834 100644
--- a/docs/api/BasicCrawler.md
+++ b/docs/api/BasicCrawler.md
@@ -2,6 +2,7 @@
id: basiccrawler
title: BasicCrawler
---
+
<a name="BasicCrawler"></a>
Provides a simple framework for parallel crawling of web pages.
@@ -34,14 +35,14 @@ parameter of the `BasicCrawler` constructor. For user convenience, the `minConcu
**Example usage:**
```javascript
-const rp = require('request-promise-native');
+const rp = require("request-promise-native");
// Prepare a list of URLs to crawl
const requestList = new Apify.RequestList({
- sources: [
- { url: 'http://www.example.com/page-1' },
- { url: 'http://www.example.com/page-2' },
- ],
+ sources: [
+ { url: "http://www.example.com/page-1" },
+ { url: "http://www.example.com/page-2" }
+ ]
});
await requestList.initialize();
@@ -53,22 +54,22 @@ const crawler = new Apify.BasicCrawler({
// Here we simply fetch the HTML of the page and store it to a dataset
await Apify.pushData({
url: request.url,
- html: await rp(request.url),
- })
- },
+ html: await rp(request.url)
+ });
+ }
});
await crawler.run();
```
-
-* [BasicCrawler](basiccrawler)
- * [`new BasicCrawler(options)`](#new_BasicCrawler_new)
- * [`.run()`](#BasicCrawler+run) ⇒ `Promise`
+- [BasicCrawler](basiccrawler)
+ - [`new BasicCrawler(options)`](#new_BasicCrawler_new)
+ - [`.run()`](#BasicCrawler+run) ⇒ `Promise`
<a name="new_BasicCrawler_new"></a>
## `new BasicCrawler(options)`
+
<table>
<thead>
<tr>
@@ -168,5 +169,5 @@ await crawler.run();
<a name="BasicCrawler+run"></a>
## `basicCrawler.run()` ⇒ `Promise`
-Runs the crawler. Returns a promise that gets resolved once all the requests are processed.
+Runs the crawler. Returns a promise that gets resolved once all the requests are processed.
diff --git a/docs/api/CheerioCrawler.md b/docs/api/CheerioCrawler.md
index af160be1a..bc92ea1e2 100644
--- a/docs/api/CheerioCrawler.md
+++ b/docs/api/CheerioCrawler.md
@@ -2,6 +2,7 @@
id: cheeriocrawler
title: CheerioCrawler
---
+
<a name="CheerioCrawler"></a>
Provides a framework for the parallel crawling of web pages using plain HTTP requests and
@@ -44,10 +45,10 @@ parameter of the `CheerioCrawler` constructor. For user convenience, the `minCon
```javascript
// Prepare a list of URLs to crawl
const requestList = new Apify.RequestList({
- sources: [
- { url: 'http://www.example.com/page-1' },
- { url: 'http://www.example.com/page-2' },
- ],
+ sources: [
+ { url: "http://www.example.com/page-1" },
+ { url: "http://www.example.com/page-2" }
+ ]
});
await requestList.initialize();
@@ -58,30 +59,34 @@ const crawler = new Apify.CheerioCrawler({
const data = [];
// Do some data extraction from the page with Cheerio.
- $('.some-collection').each((index, el) => {
- data.push({ title: $(el).find('.some-title').text() });
+ $(".some-collection").each((index, el) => {
+ data.push({
+ title: $(el)
+ .find(".some-title")
+ .text()
+ });
});
// Save the data to dataset.
await Apify.pushData({
url: request.url,
html,
- data,
- })
- },
+ data
+ });
+ }
});
await crawler.run();
```
-
-* [CheerioCrawler](cheeriocrawler)
- * [`new CheerioCrawler(options)`](#new_CheerioCrawler_new)
- * [`.run()`](#CheerioCrawler+run) ⇒ `Promise`
+- [CheerioCrawler](cheeriocrawler)
+ - [`new CheerioCrawler(options)`](#new_CheerioCrawler_new)
+ - [`.run()`](#CheerioCrawler+run) ⇒ `Promise`
<a name="new_CheerioCrawler_new"></a>
## `new CheerioCrawler(options)`
+
<table>
<thead>
<tr>
@@ -260,5 +265,5 @@ await crawler.run();
<a name="CheerioCrawler+run"></a>
## `cheerioCrawler.run()` ⇒ `Promise`
-Runs the crawler. Returns promise that gets resolved once all the requests got processed.
+Runs the crawler. Returns promise that gets resolved once all the requests got processed.
diff --git a/docs/api/Dataset.md b/docs/api/Dataset.md
index f0217b5f0..2e05b2b84 100644
--- a/docs/api/Dataset.md
+++ b/docs/api/Dataset.md
@@ -2,6 +2,7 @@
id: dataset
title: Dataset
---
+
<a name="Dataset"></a>
The `Dataset` class represents a store for structured data where each object stored has the same attributes,
@@ -18,9 +19,11 @@ depending on whether the `APIFY_LOCAL_STORAGE_DIR` or `APIFY_TOKEN` environment
If the `APIFY_LOCAL_STORAGE_DIR` environment variable is set, the data is stored in
the local directory in the following files:
+
```
{APIFY_LOCAL_STORAGE_DIR}/datasets/{DATASET_ID}/{INDEX}.json
```
+
Note that `{DATASET_ID}` is the name or ID of the dataset. The default dataset has ID: `default`,
unless you override it by setting the `APIFY_DEFAULT_DATASET_ID` environment variable.
Each dataset item is stored as a separate JSON file, where `{INDEX}` is a zero-based index of the item in the dataset.
@@ -35,34 +38,31 @@ even if the `APIFY_LOCAL_STORAGE_DIR` variable is set.
```javascript
// Write a single row to the default dataset
-await Apify.pushData({ col1: 123, col2: 'val2' });
+await Apify.pushData({ col1: 123, col2: "val2" });
// Open a named dataset
-const dataset = await Apify.openDataset('some-name');
+const dataset = await Apify.openDataset("some-name");
// Write a single row
-await dataset.pushData({ foo: 'bar' });
+await dataset.pushData({ foo: "bar" });
// Write multiple rows
-await dataset.pushData([
- { foo: 'bar2', col2: 'val2' },
- { col3: 123 },
-]);
+await dataset.pushData([{ foo: "bar2", col2: "val2" }, { col3: 123 }]);
```
-
-* [Dataset](dataset)
- * [`.pushData(data)`](#Dataset+pushData) ⇒ `Promise`
- * [`.getData([options])`](#Dataset+getData) ⇒ `Promise<Object>`
- * [`.getInfo()`](#Dataset+getInfo) ⇒ `Promise<Object>`
- * [`.forEach(iteratee, [options], [index])`](#Dataset+forEach) ⇒ `Promise`
- * [`.map(iteratee, options)`](#Dataset+map) ⇒ `Promise<Array>`
- * [`.reduce(iteratee, memo, options)`](#Dataset+reduce) ⇒ `Promise<*>`
- * [`.delete()`](#Dataset+delete) ⇒ `Promise`
+- [Dataset](dataset)
+ - [`.pushData(data)`](#Dataset+pushData) ⇒ `Promise`
+ - [`.getData([options])`](#Dataset+getData) ⇒ `Promise<Object>`
+ - [`.getInfo()`](#Dataset+getInfo) ⇒ `Promise<Object>`
+ - [`.forEach(iteratee, [options], [index])`](#Dataset+forEach) ⇒ `Promise`
+ - [`.map(iteratee, options)`](#Dataset+map) ⇒ `Promise<Array>`
+ - [`.reduce(iteratee, memo, options)`](#Dataset+reduce) ⇒ `Promise<*>`
+ - [`.delete()`](#Dataset+delete) ⇒ `Promise`
<a name="Dataset+pushData"></a>
## `dataset.pushData(data)` ⇒ `Promise`
+
Stores an object or an array of objects to the dataset.
The function returns a promise that resolves when the operation finishes.
It has no result, but throws on invalid args or other errors.
@@ -102,6 +102,7 @@ The objects must be serializable to JSON and the JSON representation of each obj
<a name="Dataset+getData"></a>
## `dataset.getData([options])` ⇒ `Promise<Object>`
+
Returns items in the dataset based on the provided parameters. The returned object
has the following structure:
@@ -218,6 +219,7 @@ If you try to use them, you will receive an error.
<a name="Dataset+getInfo"></a>
## `dataset.getInfo()` ⇒ `Promise<Object>`
+
Returns an object containing general information about the dataset.
The function returns the same object as the Apify API Client's
@@ -227,6 +229,7 @@ function, which in turn calls the
API endpoint.
**Example:**
+
```
{
id: "WkzbQMuFYuamGv3YF",
@@ -243,6 +246,7 @@ API endpoint.
<a name="Dataset+forEach"></a>
## `dataset.forEach(iteratee, [options], [index])` ⇒ `Promise`
+
Iterates over dataset items, yielding each in turn to an `iteratee` function.
Each invocation of `iteratee` is called with two arguments: `(item, index)`.
@@ -250,10 +254,11 @@ If the `iteratee` function returns a Promise then it is awaited before the next
If it throws an error, the iteration is aborted and the `forEach` function throws the error.
**Example usage**
+
```javascript
-const dataset = await Apify.openDataset('my-results');
+const dataset = await Apify.openDataset("my-results");
await dataset.forEach(async (item, index) => {
- console.log(`Item at ${index}: ${JSON.stringify(item)}`);
+ console.log(`Item at ${index}: ${JSON.stringify(item)}`);
});
```
@@ -310,6 +315,7 @@ await dataset.forEach(async (item, index) => {
<a name="Dataset+map"></a>
## `dataset.map(iteratee, options)` ⇒ `Promise<Array>`
+
Produces a new array of values by mapping each value in list through a transformation function `iteratee()`.
Each invocation of `iteratee()` is called with two arguments: `(element, index)`.
@@ -362,6 +368,7 @@ If `iteratee` returns a `Promise` then it's awaited before a next call.
<a name="Dataset+reduce"></a>
## `dataset.reduce(iteratee, memo, options)` ⇒ `Promise<*>`
+
Reduces a list of values down to a single value.
Memo is the initial state of the reduction, and each successive step of it should be returned by `iteratee()`.
@@ -424,6 +431,6 @@ If `iteratee()` returns a `Promise` then it's awaited before a next call.
<a name="Dataset+delete"></a>
## `dataset.delete()` ⇒ `Promise`
+
Removes the dataset either from the Apify cloud storage or from the local directory,
depending on the mode of operation.
-
diff --git a/docs/api/KeyValueStore.md b/docs/api/KeyValueStore.md
index a04f774b1..7fa5b84db 100644
--- a/docs/api/KeyValueStore.md
+++ b/docs/api/KeyValueStore.md
@@ -2,6 +2,7 @@
id: keyvaluestore
title: KeyValueStore
---
+
<a name="KeyValueStore"></a>
The `KeyValueStore` class represents a key-value store, a simple data storage that is used
@@ -27,9 +28,11 @@ depending on whether the `APIFY_LOCAL_STORAGE_DIR` or `APIFY_TOKEN` environment
If the `APIFY_LOCAL_STORAGE_DIR` environment variable is set, the data is stored in
the local directory in the following files:
+
```
{APIFY_LOCAL_STORAGE_DIR}/key_value_stores/{STORE_ID}/{INDEX}.{EXT}
```
+
Note that `{STORE_ID}` is the name or ID of the key-value store. The default key value store has ID: `default`,
unless you override it by setting the `APIFY_DEFAULT_KEY_VALUE_STORE_ID` environment variable.
The `{KEY}` is the key of the record and `{EXT}` corresponds to the MIME content type of the data value.
@@ -45,37 +48,37 @@ even if the `APIFY_LOCAL_STORAGE_DIR` variable is set.
```javascript
// Get actor input from the default key-value store
const input = await Apify.getInput();
-const otherValue = Apify.getValue('my-key');
+const otherValue = Apify.getValue("my-key");
// Write actor output to the default key-value store.
-await Apify.setValue('OUTPUT', { myResult: 123 });
+await Apify.setValue("OUTPUT", { myResult: 123 });
// Open a named key-value store
-const store = await Apify.openKeyValueStore('some-name');
+const store = await Apify.openKeyValueStore("some-name");
// Write a record. JavaScript object is automatically converted to JSON,
// strings and binary buffers are stored as they are
-await store.setValue('some-key', { foo: 'bar' });
+await store.setValue("some-key", { foo: "bar" });
// Read a record. Note that JSON is automatically parsed to a JavaScript object,
// text data returned as a string and other data is returned as binary buffer
-const value = await store.getValue('some-key');
+const value = await store.getValue("some-key");
- // Delete record
-await store.delete('some-key');
+// Delete record
+await store.delete("some-key");
```
-
-* [KeyValueStore](keyvaluestore)
- * [`.getValue(key)`](#KeyValueStore+getValue) ⇒ `Promise<(Object|String|Buffer)>`
- * [`.setValue(key, value, [options])`](#KeyValueStore+setValue) ⇒ `Promise`
- * [`.delete()`](#KeyValueStore+delete) ⇒ `Promise`
- * [`.getPublicUrl(key)`](#KeyValueStore+getPublicUrl) ⇒ `string`
- * [`.forEachKey(iteratee, [options])`](#KeyValueStore+forEachKey) ⇒ `Promise`
+- [KeyValueStore](keyvaluestore)
+ - [`.getValue(key)`](#KeyValueStore+getValue) ⇒ `Promise<(Object|String|Buffer)>`
+ - [`.setValue(key, value, [options])`](#KeyValueStore+setValue) ⇒ `Promise`
+ - [`.delete()`](#KeyValueStore+delete) ⇒ `Promise`
+ - [`.getPublicUrl(key)`](#KeyValueStore+getPublicUrl) ⇒ `string`
+ - [`.forEachKey(iteratee, [options])`](#KeyValueStore+forEachKey) ⇒ `Promise`
<a name="KeyValueStore+getValue"></a>
## `keyValueStore.getValue(key)` ⇒ `Promise<(Object|String|Buffer)>`
+
Gets a value from the key-value store.
The function returns a `Promise` that resolves to the record value,
@@ -94,13 +97,14 @@ To save or delete a value in the key-value store, use the
**Example usage:**
```javascript
-const store = await Apify.openKeyValueStore('my-screenshots');
-const buffer = await store.getValue('screenshot1.png');
+const store = await Apify.openKeyValueStore("my-screenshots");
+const buffer = await store.getValue("screenshot1.png");
```
**Returns**: `Promise<(Object|String|Buffer)>` - Returns a promise that resolves to an object, string
- or <a href="https://nodejs.org/api/buffer.html" target="_blank"><code>Buffer</code></a>, depending
- on the MIME content type of the record.
+or <a href="https://nodejs.org/api/buffer.html" target="_blank"><code>Buffer</code></a>, depending
+on the MIME content type of the record.
+
<table>
<thead>
<tr>
@@ -119,14 +123,15 @@ const buffer = await store.getValue('screenshot1.png');
<a name="KeyValueStore+setValue"></a>
## `keyValueStore.setValue(key, value, [options])` ⇒ `Promise`
+
Saves or deletes a record in the key-value store.
The function returns a promise that resolves once the record has been saved or deleted.
**Example usage:**
```javascript
-const store = await Apify.openKeyValueStore('my-store');
-await store.setValue('RESULTS', 'my text data', { contentType: 'text/plain' });
+const store = await Apify.openKeyValueStore("my-store");
+await store.setValue("RESULTS", "my text data", { contentType: "text/plain" });
```
Beware that the key can be at most 256 characters long and only contain the following characters: `a-zA-Z0-9!-_.'()`
@@ -134,10 +139,12 @@ Beware that the key can be at most 256 characters long and only contain the foll
By default, `value` is converted to JSON and stored with the
`application/json; charset=utf-8` MIME content type.
To store the value with another content type, pass it in the options as follows:
+
```javascript
-const store = await Apify.openKeyValueStore('my-store');
-await store.setValue('RESULTS', 'my text data', { contentType: 'text/plain' });
+const store = await Apify.openKeyValueStore("my-store");
+await store.setValue("RESULTS", "my text data", { contentType: "text/plain" });
```
+
If you set custom content type, `value` must be either a string or
<a href="https://nodejs.org/api/buffer.html" target="_blank"><code>Buffer</code></a>, otherwise an error will be thrown.
@@ -189,12 +196,14 @@ otherwise the actor process might finish before the value is stored!
<a name="KeyValueStore+delete"></a>
## `keyValueStore.delete()` ⇒ `Promise`
+
Removes the key-value store either from the Apify cloud storage or from the local directory,
depending on the mode of operation.
<a name="KeyValueStore+getPublicUrl"></a>
## `keyValueStore.getPublicUrl(key)` ⇒ `string`
+
Returns a URL for the given key that may be used to publicly
access the value in the remote key value store.
@@ -214,6 +223,7 @@ access the value in the remote key value store.
<a name="KeyValueStore+forEachKey"></a>
## `keyValueStore.forEachKey(iteratee, [options])` ⇒ `Promise`
+
Iterates over key value store keys, yielding each in turn to an `iteratee` function.
Each invocation of `iteratee` is called with three arguments: `(key, index, info)`, where `key`
is the record key, `index` is a zero-based index of the key in the current iteration
@@ -224,10 +234,11 @@ If the `iteratee` function returns a Promise then it is awaited before the next
If it throws an error, the iteration is aborted and the `forEachKey` function throws the error.
**Example usage**
+
```javascript
const keyValueStore = await Apify.openKeyValueStore();
await keyValueStore.forEachKey(async (key, index, info) => {
- console.log(`Key at ${index}: ${key} has size ${info.size}`);
+ console.log(`Key at ${index}: ${key} has size ${info.size}`);
});
```
diff --git a/docs/api/LiveViewServer.md b/docs/api/LiveViewServer.md
index 3a9357003..d531e12e5 100644
--- a/docs/api/LiveViewServer.md
+++ b/docs/api/LiveViewServer.md
@@ -2,6 +2,7 @@
id: liveviewserver
title: LiveViewServer
---
+
<a name="LiveViewServer"></a>
`LiveViewServer` enables serving of browser snapshots via web sockets. It includes its own client
@@ -35,18 +36,18 @@ single page improves performance and stability dramatically in high concurrency
When running locally, it is often best to use a headful browser for debugging, since it provides
a better view into the browser, including DevTools, but `LiveViewServer` works too.
-
-* [LiveViewServer](liveviewserver)
- * [`new LiveViewServer([options])`](#new_LiveViewServer_new)
- * [`.start()`](#LiveViewServer+start) ⇒ `Promise`
- * [`.stop()`](#LiveViewServer+stop) ⇒ `Promise`
- * [`.serve(page)`](#LiveViewServer+serve) ⇒ `Promise`
- * [`.isRunning()`](#LiveViewServer+isRunning) ⇒ `boolean`
- * [`.hasClients()`](#LiveViewServer+hasClients) ⇒ `boolean`
+- [LiveViewServer](liveviewserver)
+ - [`new LiveViewServer([options])`](#new_LiveViewServer_new)
+ - [`.start()`](#LiveViewServer+start) ⇒ `Promise`
+ - [`.stop()`](#LiveViewServer+stop) ⇒ `Promise`
+ - [`.serve(page)`](#LiveViewServer+serve) ⇒ `Promise`
+ - [`.isRunning()`](#LiveViewServer+isRunning) ⇒ `boolean`
+ - [`.hasClients()`](#LiveViewServer+hasClients) ⇒ `boolean`
<a name="new_LiveViewServer_new"></a>
## `new LiveViewServer([options])`
+
<table>
<thead>
<tr>
@@ -92,18 +93,21 @@ a better view into the browser, including DevTools, but `LiveViewServer` works t
<a name="LiveViewServer+start"></a>
## `liveViewServer.start()` ⇒ `Promise`
+
Starts the HTTP server with web socket connections enabled.
Snapshots will not be created until a client has connected.
<a name="LiveViewServer+stop"></a>
## `liveViewServer.stop()` ⇒ `Promise`
+
Prevents the server from receiving more connections. Existing connections
will not be terminated, but the server will not prevent a process exit.
<a name="LiveViewServer+serve"></a>
## `liveViewServer.serve(page)` ⇒ `Promise`
+
Serves a snapshot to all connected clients.
Screenshots are not served directly, only their index number
which is used by client to retrieve the screenshot.
@@ -126,6 +130,7 @@ Will time out and throw in `options.snapshotTimeoutSecs`.
<a name="LiveViewServer+isRunning"></a>
## `liveViewServer.isRunning()` ⇒ `boolean`
+
<a name="LiveViewServer+hasClients"></a>
## `liveViewServer.hasClients()` ⇒ `boolean`
diff --git a/docs/api/PseudoUrl.md b/docs/api/PseudoUrl.md
index 34a947f03..7f400ac2e 100644
--- a/docs/api/PseudoUrl.md
+++ b/docs/api/PseudoUrl.md
@@ -2,6 +2,7 @@
id: pseudourl
title: PseudoUrl
---
+
<a name="PseudoUrl"></a>
Represents a pseudo-URL (PURL) - an URL pattern used by web crawlers
@@ -28,10 +29,13 @@ For example, a PURL `http://www.example.com/pages/[(\w|-)*]` will match all of t
Be careful to correctly escape special characters in the pseudo-URL string.
If either `[` or `]` is part of the normal query string, it must be encoded as `[\x5B]` or `[\x5D]`,
respectively. For example, the following PURL:
+
```http
http://www.example.com/search?do[\x5B]load[\x5D]=1
```
+
will match the URL:
+
```http
http://www.example.com/search?do[load]=1
```
@@ -43,25 +47,26 @@ you need to escape it with another back backslash, as shown in the example below
```javascript
// Using a pseudo-URL string
-const purl = new Apify.PseudoUrl('http://www.example.com/pages/[(\\w|-)+]', {
- userData: { foo: 'bar' },
+const purl = new Apify.PseudoUrl("http://www.example.com/pages/[(\\w|-)+]", {
+ userData: { foo: "bar" }
});
// Using a regular expression
const purl2 = new Apify.PseudoUrl(/http:\/\/www\.example\.com\/pages\/(\w|-)+/);
-if (purl.matches('http://www.example.com/pages/my-awesome-page')) console.log('Match!');
+if (purl.matches("http://www.example.com/pages/my-awesome-page"))
+ console.log("Match!");
```
-
-* [PseudoUrl](pseudourl)
- * [`new PseudoUrl(purl, requestTemplate)`](#new_PseudoUrl_new)
- * [`.matches(url)`](#PseudoUrl+matches) ⇒ `Boolean`
- * [`.createRequest(urlOrProps)`](#PseudoUrl+createRequest) ⇒ [`Request`](request)
+- [PseudoUrl](pseudourl)
+ - [`new PseudoUrl(purl, requestTemplate)`](#new_PseudoUrl_new)
+ - [`.matches(url)`](#PseudoUrl+matches) ⇒ `Boolean`
+ - [`.createRequest(urlOrProps)`](#PseudoUrl+createRequest) ⇒ [`Request`](request)
<a name="new_PseudoUrl_new"></a>
## `new PseudoUrl(purl, requestTemplate)`
+
<table>
<thead>
<tr>
@@ -87,9 +92,11 @@ if (purl.matches('http://www.example.com/pages/my-awesome-page')) console.log('M
<a name="PseudoUrl+matches"></a>
## `pseudoUrl.matches(url)` ⇒ `Boolean`
+
Determines whether a URL matches this pseudo-URL pattern.
-**Returns**: `Boolean` - Returns `true` if given URL matches pseudo-URL.
+**Returns**: `Boolean` - Returns `true` if given URL matches pseudo-URL.
+
<table>
<thead>
<tr>
@@ -107,8 +114,9 @@ Determines whether a URL matches this pseudo-URL pattern.
<a name="PseudoUrl+createRequest"></a>
## `pseudoUrl.createRequest(urlOrProps)` ⇒ [`Request`](request)
+
Creates a Request object from a provided `requestTemplate` and a given URL
-or an object that specifies $[`Request`](request) properties. In case of a collision
+or an object that specifies \$[`Request`](request) properties. In case of a collision
the properties will override the template, except for `userData`, which will
be merged together, with the `userData` property having preference over the template.
This enables dynamic overriding of the template.
diff --git a/docs/api/PuppeteerCrawler.md b/docs/api/PuppeteerCrawler.md
index 374817028..2f8d9c5ed 100644
--- a/docs/api/PuppeteerCrawler.md
+++ b/docs/api/PuppeteerCrawler.md
@@ -2,6 +2,7 @@
id: puppeteercrawler
title: PuppeteerCrawler
---
+
<a name="PuppeteerCrawler"></a>
Provides a simple framework for parallel crawling of web pages
@@ -50,30 +51,30 @@ const crawler = new Apify.PuppeteerCrawler({
await Apify.pushData({
title: await page.title(),
url: request.url,
- succeeded: true,
- })
+ succeeded: true
+ });
},
handleFailedRequestFunction: async ({ request }) => {
// This function is called when the crawling of a request failed too many times
await Apify.pushData({
url: request.url,
succeeded: false,
- errors: request.errorMessages,
- })
- },
+ errors: request.errorMessages
+ });
+ }
});
await crawler.run();
```
-
-* [PuppeteerCrawler](puppeteercrawler)
- * [`new PuppeteerCrawler(options)`](#new_PuppeteerCrawler_new)
- * [`.run()`](#PuppeteerCrawler+run) ⇒ `Promise`
+- [PuppeteerCrawler](puppeteercrawler)
+ - [`new PuppeteerCrawler(options)`](#new_PuppeteerCrawler_new)
+ - [`.run()`](#PuppeteerCrawler+run) ⇒ `Promise`
<a name="new_PuppeteerCrawler_new"></a>
## `new PuppeteerCrawler(options)`
+
<table>
<thead>
<tr>
@@ -215,5 +216,5 @@ await crawler.run();
<a name="PuppeteerCrawler+run"></a>
## `puppeteerCrawler.run()` ⇒ `Promise`
-Runs the crawler. Returns promise that gets resolved once all the requests got processed.
+Runs the crawler. Returns promise that gets resolved once all the requests got processed.
diff --git a/docs/api/PuppeteerPool.md b/docs/api/PuppeteerPool.md
index ee6bb8d34..a97ed2bed 100644
--- a/docs/api/PuppeteerPool.md
+++ b/docs/api/PuppeteerPool.md
@@ -2,6 +2,7 @@
id: puppeteerpool
title: PuppeteerPool
---
+
<a name="PuppeteerPool"></a>
Manages a pool of Chrome browser instances controlled using
@@ -21,12 +22,12 @@ and the retirement of instances helps mitigate effects of memory leaks in Chrome
```javascript
const puppeteerPool = new PuppeteerPool({
- launchPuppeteerFunction: () => {
- // Use a new proxy with a new IP address for each new Chrome instance
- return Apify.launchPuppeteer({
- apifyProxySession: Math.random(),
- });
- },
+ launchPuppeteerFunction: () => {
+ // Use a new proxy with a new IP address for each new Chrome instance
+ return Apify.launchPuppeteer({
+ apifyProxySession: Math.random()
+ });
+ }
});
const page1 = await puppeteerPool.newPage();
@@ -39,18 +40,18 @@ const page3 = await puppeteerPool.newPage();
await puppeteerPool.destroy();
```
-
-* [PuppeteerPool](puppeteerpool)
- * [`new PuppeteerPool([options])`](#new_PuppeteerPool_new)
- * [`.newPage()`](#PuppeteerPool+newPage) ⇒ `Promise<Page>`
- * [`.destroy()`](#PuppeteerPool+destroy) ⇒ `Promise`
- * [`.retire(browser)`](#PuppeteerPool+retire) ⇒ `Promise`
- * [`.recyclePage(page)`](#PuppeteerPool+recyclePage) ⇒ `Promise`
- * [`.serveLiveViewSnapshot(page)`](#PuppeteerPool+serveLiveViewSnapshot) ⇒ `Promise`
+- [PuppeteerPool](puppeteerpool)
+ - [`new PuppeteerPool([options])`](#new_PuppeteerPool_new)
+ - [`.newPage()`](#PuppeteerPool+newPage) ⇒ `Promise<Page>`
+ - [`.destroy()`](#PuppeteerPool+destroy) ⇒ `Promise`
+ - [`.retire(browser)`](#PuppeteerPool+retire) ⇒ `Promise`
+ - [`.recyclePage(page)`](#PuppeteerPool+recyclePage) ⇒ `Promise`
+ - [`.serveLiveViewSnapshot(page)`](#PuppeteerPool+serveLiveViewSnapshot) ⇒ `Promise`
<a name="new_PuppeteerPool_new"></a>
## `new PuppeteerPool([options])`
+
<table>
<thead>
<tr>
@@ -145,6 +146,7 @@ await puppeteerPool.destroy();
<a name="PuppeteerPool+newPage"></a>
## `puppeteerPool.newPage()` ⇒ `Promise<Page>`
+
Produces a new page instance either by reusing an idle page that currently isn't processing
any request or by spawning a new page (new browser tab) in one of the available
browsers when no idle pages are available.
@@ -154,11 +156,13 @@ To spawn a new browser tab for each page, set the `reusePages` constructor optio
<a name="PuppeteerPool+destroy"></a>
## `puppeteerPool.destroy()` ⇒ `Promise`
+
Closes all open browsers.
<a name="PuppeteerPool+retire"></a>
## `puppeteerPool.retire(browser)` ⇒ `Promise`
+
Manually retires a Puppeteer
<a href="https://pptr.dev/#?product=Puppeteer&show=api-class-browser" target="_blank"><code>Browser</code></a>
instance from the pool. The browser will continue to process open pages so that they may gracefully finish.
@@ -180,6 +184,7 @@ This is unlike `browser.close()` which will forcibly terminate the browser and a
<a name="PuppeteerPool+recyclePage"></a>
## `puppeteerPool.recyclePage(page)` ⇒ `Promise`
+
Closes the page, unless the `reuseTabs` option is set to true.
Then it would only flag the page for a future reuse, without actually closing it.
@@ -203,6 +208,7 @@ or flagging it for reuse.
<a name="PuppeteerPool+serveLiveViewSnapshot"></a>
## `puppeteerPool.serveLiveViewSnapshot(page)` ⇒ `Promise`
+
Tells the connected LiveViewServer to serve a snapshot when available.
<table>
diff --git a/docs/api/Request.md b/docs/api/Request.md
index 1c9c47180..74a900134 100644
--- a/docs/api/Request.md
+++ b/docs/api/Request.md
@@ -2,6 +2,7 @@
id: request
title: Request
---
+
<a name="Request"></a>
Represents a URL to be crawled, optionally including HTTP method, headers, payload and other metadata.
@@ -31,6 +32,7 @@ const foo = request.userData.foo;
```
**Properties**
+
<table>
<thead>
<tr>
@@ -107,14 +109,15 @@ const foo = request.userData.foo;
</td></tr></tbody>
</table>
-* [Request](request)
- * [`new Request(options)`](#new_Request_new)
- * [`.pushErrorMessage(errorOrMessage, [options])`](#Request+pushErrorMessage)
- * ~~[`.doNotRetry([message])`](#Request+doNotRetry)~~
+- [Request](request)
+ - [`new Request(options)`](#new_Request_new)
+ - [`.pushErrorMessage(errorOrMessage, [options])`](#Request+pushErrorMessage)
+ - ~~[`.doNotRetry([message])`](#Request+doNotRetry)~~
<a name="new_Request_new"></a>
## `new Request(options)`
+
<table>
<thead>
<tr>
@@ -191,6 +194,7 @@ to override the default behavior and specify which URLs shall be considered equa
<a name="Request+pushErrorMessage"></a>
## `request.pushErrorMessage(errorOrMessage, [options])`
+
Stores information about an error that occurred during processing of this request.
You should always use Error instances when throwing errors in JavaScript.
@@ -226,7 +230,8 @@ as possible, since just throwing a bad type error makes any debugging rather dif
<a name="Request+doNotRetry"></a>
## ~~`request.doNotRetry([message])`~~
-***Deprecated***
+
+**_Deprecated_**
Flags the request with no retry which prevents [`BasicCrawler`](basiccrawler)
(as well as {@PuppeteerCrawler} and {@CheerioCrawler}, since they use {@BasicCrawler} internally)
diff --git a/docs/api/RequestList.md b/docs/api/RequestList.md
index c69017d52..b65aaca77 100644
--- a/docs/api/RequestList.md
+++ b/docs/api/RequestList.md
@@ -2,6 +2,7 @@
id: requestlist
title: RequestList
---
+
<a name="RequestList"></a>
Represents a static list of URLs to crawl.
@@ -40,15 +41,18 @@ which will prevent any issues that a live list of URLs might cause.
const requestList = new Apify.RequestList({
sources: [
// Separate requests
- { url: 'http://www.example.com/page-1', method: 'GET', headers: {} },
- { url: 'http://www.example.com/page-2', userData: { foo: 'bar' }},
+ { url: "http://www.example.com/page-1", method: "GET", headers: {} },
+ { url: "http://www.example.com/page-2", userData: { foo: "bar" } },
// Bulk load of URLs from file `http://www.example.com/my-url-list.txt`
// Note that all URLs must start with http:// or https://
- { requestsFromUrl: 'http://www.example.com/my-url-list.txt', userData: { isFromUrl: true } },
+ {
+ requestsFromUrl: "http://www.example.com/my-url-list.txt",
+ userData: { isFromUrl: true }
+ }
],
- persistStateKey: 'my-state',
- persistSourcesKey: 'my-sources'
+ persistStateKey: "my-state",
+ persistSourcesKey: "my-sources"
});
// This call loads and parses the URLs from the remote file.
@@ -66,23 +70,23 @@ await requestList.markRequestHandled(request1);
await requestList.reclaimRequest(request2);
```
-
-* [RequestList](requestlist)
- * [`new exports.RequestList(options)`](#new_RequestList_new)
- * [`.initialize()`](#RequestList+initialize) ⇒ `Promise`
- * [`.persistState()`](#RequestList+persistState) ⇒ `Promise`
- * [`.getState()`](#RequestList+getState) ⇒ `Object`
- * [`.isEmpty()`](#RequestList+isEmpty) ⇒ `Promise<Boolean>`
- * [`.isFinished()`](#RequestList+isFinished) ⇒ `Promise<Boolean>`
- * [`.fetchNextRequest()`](#RequestList+fetchNextRequest) ⇒ [`Promise<Request>`](request)
- * [`.markRequestHandled(request)`](#RequestList+markRequestHandled) ⇒ `Promise`
- * [`.reclaimRequest(request)`](#RequestList+reclaimRequest) ⇒ `Promise`
- * [`.length()`](#RequestList+length) ⇒ `Number`
- * [`.handledCount()`](#RequestList+handledCount) ⇒ `Number`
+- [RequestList](requestlist)
+ - [`new exports.RequestList(options)`](#new_RequestList_new)
+ - [`.initialize()`](#RequestList+initialize) ⇒ `Promise`
+ - [`.persistState()`](#RequestList+persistState) ⇒ `Promise`
+ - [`.getState()`](#RequestList+getState) ⇒ `Object`
+ - [`.isEmpty()`](#RequestList+isEmpty) ⇒ `Promise<Boolean>`
+ - [`.isFinished()`](#RequestList+isFinished) ⇒ `Promise<Boolean>`
+ - [`.fetchNextRequest()`](#RequestList+fetchNextRequest) ⇒ [`Promise<Request>`](request)
+ - [`.markRequestHandled(request)`](#RequestList+markRequestHandled) ⇒ `Promise`
+ - [`.reclaimRequest(request)`](#RequestList+reclaimRequest) ⇒ `Promise`
+ - [`.length()`](#RequestList+length) ⇒ `Number`
+ - [`.handledCount()`](#RequestList+handledCount) ⇒ `Number`
<a name="new_RequestList_new"></a>
## `new exports.RequestList(options)`
+
<table>
<thead>
<tr>
@@ -159,12 +163,14 @@ await requestList.reclaimRequest(request2);
<a name="RequestList+initialize"></a>
## `requestList.initialize()` ⇒ `Promise`
+
Loads all remote sources of URLs and potentially starts periodic state persistence.
This function must be called before you can start using the instance in a meaningful way.
<a name="RequestList+persistState"></a>
## `requestList.persistState()` ⇒ `Promise`
+
Persists the current state of the `RequestList` into the default [`KeyValueStore`](keyvaluestore).
The state is persisted automatically in regular intervals, but calling this method manually
is useful in cases where you want to have the most current state available after you pause
@@ -174,12 +180,14 @@ a server migration.
<a name="RequestList+getState"></a>
## `requestList.getState()` ⇒ `Object`
+
Returns an object representing the internal state of the `RequestList` instance.
Note that the object's fields can change in future releases.
<a name="RequestList+isEmpty"></a>
## `requestList.isEmpty()` ⇒ `Promise<Boolean>`
+
Resolves to `true` if the next call to [`fetchNextRequest`](#RequestList+fetchNextRequest) function
would return `null`, otherwise it resolves to `false`.
Note that even if the list is empty, there might be some pending requests currently being processed.
@@ -187,11 +195,13 @@ Note that even if the list is empty, there might be some pending requests curren
<a name="RequestList+isFinished"></a>
## `requestList.isFinished()` ⇒ `Promise<Boolean>`
+
Returns `true` if all requests were already handled and there are no more left.
<a name="RequestList+fetchNextRequest"></a>
## `requestList.fetchNextRequest()` ⇒ [`Promise<Request>`](request)
+
Gets the next [`Request`](request) to process. First, the function gets a request previously reclaimed
using the [`reclaimRequest`](#RequestList+reclaimRequest) function, if there is any.
Otherwise it gets the next request from sources.
@@ -202,6 +212,7 @@ requests to process.
<a name="RequestList+markRequestHandled"></a>
## `requestList.markRequestHandled(request)` ⇒ `Promise`
+
Marks request as handled after successful processing.
<table>
@@ -220,6 +231,7 @@ Marks request as handled after successful processing.
<a name="RequestList+reclaimRequest"></a>
## `requestList.reclaimRequest(request)` ⇒ `Promise`
+
Reclaims request to the list if its processing failed.
The request will become available in the next `this.fetchNextRequest()`.
@@ -239,10 +251,11 @@ The request will become available in the next `this.fetchNextRequest()`.
<a name="RequestList+length"></a>
## `requestList.length()` ⇒ `Number`
+
Returns the total number of unique requests present in the `RequestList`.
<a name="RequestList+handledCount"></a>
## `requestList.handledCount()` ⇒ `Number`
-Returns number of handled requests.
+Returns number of handled requests.
diff --git a/docs/api/RequestQueue.md b/docs/api/RequestQueue.md
index 79cac7229..01cf3632c 100644
--- a/docs/api/RequestQueue.md
+++ b/docs/api/RequestQueue.md
@@ -2,6 +2,7 @@
id: requestqueue
title: RequestQueue
---
+
<a name="RequestQueue"></a>
Represents a queue of URLs to crawl, which is used for deep crawling of websites
@@ -27,9 +28,11 @@ depending on whether the `APIFY_LOCAL_STORAGE_DIR` or `APIFY_TOKEN` environment
If the `APIFY_LOCAL_STORAGE_DIR` environment variable is set, the queue data is stored in
that local directory as follows:
+
```
{APIFY_LOCAL_STORAGE_DIR}/request_queues/{QUEUE_ID}/{STATE}/{NUMBER}.json
```
+
Note that `{QUEUE_ID}` is the name or ID of the request queue. The default queue has ID: `default`,
unless you override it by setting the `APIFY_DEFAULT_REQUEST_QUEUE_ID` environment variable.
Each request in the queue is stored as a separate JSON file, where `{STATE}` is either `handled` or `pending`,
@@ -48,12 +51,15 @@ even if the `APIFY_LOCAL_STORAGE_DIR` variable is set.
const queue = await Apify.openRequestQueue();
// Open a named request queue
-const queueWithName = await Apify.openRequestQueue('some-name');
+const queueWithName = await Apify.openRequestQueue("some-name");
// Enqueue few requests
-await queue.addRequest({ url: 'http://example.com/aaa' });
-await queue.addRequest({ url: 'http://example.com/bbb' });
-await queue.addRequest({ url: 'http://example.com/foo/bar' }, { forefront: true });
+await queue.addRequest({ url: "http://example.com/aaa" });
+await queue.addRequest({ url: "http://example.com/bbb" });
+await queue.addRequest(
+ { url: "http://example.com/foo/bar" },
+ { forefront: true }
+);
// Get requests from queue
const request1 = await queue.fetchNextRequest();
@@ -67,22 +73,22 @@ await queue.markRequestHandled(request1);
await queue.reclaimRequest(request2);
```
-
-* [RequestQueue](requestqueue)
- * [`.addRequest(request, [options])`](#RequestQueue+addRequest) ⇒ [`QueueOperationInfo`](../typedefs/queueoperationinfo)
- * [`.getRequest(requestId)`](#RequestQueue+getRequest) ⇒ [`Promise<Request>`](request)
- * [`.fetchNextRequest()`](#RequestQueue+fetchNextRequest) ⇒ [`Promise<Request>`](request)
- * [`.markRequestHandled(request)`](#RequestQueue+markRequestHandled) ⇒ [`Promise<QueueOperationInfo>`](../typedefs/queueoperationinfo)
- * [`.reclaimRequest(request, [options])`](#RequestQueue+reclaimRequest) ⇒ [`Promise<QueueOperationInfo>`](../typedefs/queueoperationinfo)
- * [`.isEmpty()`](#RequestQueue+isEmpty) ⇒ `Promise<Boolean>`
- * [`.isFinished()`](#RequestQueue+isFinished) ⇒ `Promise<Boolean>`
- * [`.delete()`](#RequestQueue+delete) ⇒ `Promise`
- * ~~[`.handledCount()`](#RequestQueue+handledCount) ⇒ `Promise<number>`~~
- * [`.getInfo()`](#RequestQueue+getInfo) ⇒ `Promise<Object>`
+- [RequestQueue](requestqueue)
+ - [`.addRequest(request, [options])`](#RequestQueue+addRequest) ⇒ [`QueueOperationInfo`](../typedefs/queueoperationinfo)
+ - [`.getRequest(requestId)`](#RequestQueue+getRequest) ⇒ [`Promise<Request>`](request)
+ - [`.fetchNextRequest()`](#RequestQueue+fetchNextRequest) ⇒ [`Promise<Request>`](request)
+ - [`.markRequestHandled(request)`](#RequestQueue+markRequestHandled) ⇒ [`Promise<QueueOperationInfo>`](../typedefs/queueoperationinfo)
+ - [`.reclaimRequest(request, [options])`](#RequestQueue+reclaimRequest) ⇒ [`Promise<QueueOperationInfo>`](../typedefs/queueoperationinfo)
+ - [`.isEmpty()`](#RequestQueue+isEmpty) ⇒ `Promise<Boolean>`
+ - [`.isFinished()`](#RequestQueue+isFinished) ⇒ `Promise<Boolean>`
+ - [`.delete()`](#RequestQueue+delete) ⇒ `Promise`
+ - ~~[`.handledCount()`](#RequestQueue+handledCount) ⇒ `Promise<number>`~~
+ - [`.getInfo()`](#RequestQueue+getInfo) ⇒ `Promise<Object>`
<a name="RequestQueue+addRequest"></a>
## `requestQueue.addRequest(request, [options])` ⇒ [`QueueOperationInfo`](../typedefs/queueoperationinfo)
+
Adds a request to the queue.
If a request with the same `uniqueKey` property is already present in the queue,
@@ -116,9 +122,11 @@ Note that the function sets the <code>uniqueKey</code> and <code>id</code> field
<a name="RequestQueue+getRequest"></a>
## `requestQueue.getRequest(requestId)` ⇒ [`Promise<Request>`](request)
+
Gets the request from the queue specified by ID.
-**Returns**: [`Promise<Request>`](request) - Returns the request object, or `null` if it was not found.
+**Returns**: [`Promise<Request>`](request) - Returns the request object, or `null` if it was not found.
+
<table>
<thead>
<tr>
@@ -136,6 +144,7 @@ Gets the request from the queue specified by ID.
<a name="RequestQueue+fetchNextRequest"></a>
## `requestQueue.fetchNextRequest()` ⇒ [`Promise<Request>`](request)
+
Returns a next request in the queue to be processed, or `null` if there are no more pending requests.
Once you successfully finish processing of the request, you need to call [`RequestQueue.markRequestHandled`](requestqueue.markrequesthandled)
@@ -151,6 +160,7 @@ To check whether all requests in queue were finished, use [`RequestQueue.isFinis
<a name="RequestQueue+markRequestHandled"></a>
## `requestQueue.markRequestHandled(request)` ⇒ [`Promise<QueueOperationInfo>`](../typedefs/queueoperationinfo)
+
Marks a request that was previously returned by the [`RequestQueue.fetchNextRequest`](requestqueue.fetchnextrequest) function
as handled after successful processing.
Handled requests will never again be returned by the `fetchNextRequest` function.
@@ -171,6 +181,7 @@ Handled requests will never again be returned by the `fetchNextRequest` function
<a name="RequestQueue+reclaimRequest"></a>
## `requestQueue.reclaimRequest(request, [options])` ⇒ [`Promise<QueueOperationInfo>`](../typedefs/queueoperationinfo)
+
Reclaims a failed request back to the queue, so that it can be returned for processed later again
by another call to [`RequestQueue.fetchNextRequest`](requestqueue.fetchnextrequest).
The request record in the queue is updated using the provided `request` parameter.
@@ -202,6 +213,7 @@ in the next call to <a href="requestqueue.fetchnextrequest"><code>RequestQueue.f
<a name="RequestQueue+isEmpty"></a>
## `requestQueue.isEmpty()` ⇒ `Promise<Boolean>`
+
Resolves to `true` if the next call to [`RequestQueue.fetchNextRequest`](requestqueue.fetchnextrequest) would return `null`, otherwise it resolves to `false`.
Note that even if the queue is empty, there might be some pending requests currently being processed.
If you need to ensure that there is no activity in the queue, use [`RequestQueue.isFinished`](requestqueue.isfinished).
@@ -209,6 +221,7 @@ If you need to ensure that there is no activity in the queue, use [`RequestQueue
<a name="RequestQueue+isFinished"></a>
## `requestQueue.isFinished()` ⇒ `Promise<Boolean>`
+
Resolves to `true` if all requests were already handled and there are no more left.
Due to the nature of distributed storage used by the queue,
the function might occasionally return a false negative,
@@ -217,13 +230,15 @@ but it will never return a false positive.
<a name="RequestQueue+delete"></a>
## `requestQueue.delete()` ⇒ `Promise`
+
Removes the queue either from the Apify Cloud storage or from the local directory,
depending on the mode of operation.
<a name="RequestQueue+handledCount"></a>
## ~~`requestQueue.handledCount()` ⇒ `Promise<number>`~~
-***Deprecated***
+
+**_Deprecated_**
Returns the number of handled requests.
@@ -236,6 +251,7 @@ const { handledRequestCount } = await queue.getInfo();
<a name="RequestQueue+getInfo"></a>
## `requestQueue.getInfo()` ⇒ `Promise<Object>`
+
Returns an object containing general information about the request queue.
The function returns the same object as the Apify API Client's
@@ -245,6 +261,7 @@ function, which in turn calls the
API endpoint.
**Example:**
+
```
{
id: "WkzbQMuFYuamGv3YF",
@@ -258,4 +275,3 @@ API endpoint.
pendingRequestCount: 20,
}
```
-
diff --git a/docs/api/Snapshotter.md b/docs/api/Snapshotter.md
index 6418be907..fffbc01e9 100644
--- a/docs/api/Snapshotter.md
+++ b/docs/api/Snapshotter.md
@@ -2,6 +2,7 @@
id: snapshotter
title: Snapshotter
---
+
<a name="Snapshotter"></a>
Creates snapshots of system resources at given intervals and marks the resource
@@ -27,19 +28,19 @@ Event loop becomes overloaded if it slows down by more than the `maxBlockedMilli
Client becomes overloaded when rate limit errors (429 - Too Many Requests),
typically received from the request queue, exceed the set limit within the set interval.
-
-* [Snapshotter](snapshotter)
- * [`new Snapshotter([options])`](#new_Snapshotter_new)
- * [`.start()`](#Snapshotter+start) ⇒ `Promise`
- * [`.stop()`](#Snapshotter+stop) ⇒ `Promise`
- * [`.getMemorySample([sampleDurationMillis])`](#Snapshotter+getMemorySample) ⇒ `Array`
- * [`.getEventLoopSample([sampleDurationMillis])`](#Snapshotter+getEventLoopSample) ⇒ `Array`
- * [`.getCpuSample([sampleDurationMillis])`](#Snapshotter+getCpuSample) ⇒ `Array`
- * [`.getClientSample(sampleDurationMillis)`](#Snapshotter+getClientSample) ⇒ `Array`
+- [Snapshotter](snapshotter)
+ - [`new Snapshotter([options])`](#new_Snapshotter_new)
+ - [`.start()`](#Snapshotter+start) ⇒ `Promise`
+ - [`.stop()`](#Snapshotter+stop) ⇒ `Promise`
+ - [`.getMemorySample([sampleDurationMillis])`](#Snapshotter+getMemorySample) ⇒ `Array`
+ - [`.getEventLoopSample([sampleDurationMillis])`](#Snapshotter+getEventLoopSample) ⇒ `Array`
+ - [`.getCpuSample([sampleDurationMillis])`](#Snapshotter+getCpuSample) ⇒ `Array`
+ - [`.getClientSample(sampleDurationMillis)`](#Snapshotter+getClientSample) ⇒ `Array`
<a name="new_Snapshotter_new"></a>
## `new Snapshotter([options])`
+
<table>
<thead>
<tr>
@@ -115,16 +116,19 @@ typically received from the request queue, exceed the set limit within the set i
<a name="Snapshotter+start"></a>
## `snapshotter.start()` ⇒ `Promise`
+
Starts capturing snapshots at configured intervals.
<a name="Snapshotter+stop"></a>
## `snapshotter.stop()` ⇒ `Promise`
+
Stops all resource capturing.
<a name="Snapshotter+getMemorySample"></a>
## `snapshotter.getMemorySample([sampleDurationMillis])` ⇒ `Array`
+
Returns a sample of latest memory snapshots, with the size of the sample defined
by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.
@@ -144,6 +148,7 @@ by the sampleDurationMillis parameter. If omitted, it returns a full snapshot hi
<a name="Snapshotter+getEventLoopSample"></a>
## `snapshotter.getEventLoopSample([sampleDurationMillis])` ⇒ `Array`
+
Returns a sample of latest event loop snapshots, with the size of the sample defined
by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.
@@ -163,6 +168,7 @@ by the sampleDurationMillis parameter. If omitted, it returns a full snapshot hi
<a name="Snapshotter+getCpuSample"></a>
## `snapshotter.getCpuSample([sampleDurationMillis])` ⇒ `Array`
+
Returns a sample of latest CPU snapshots, with the size of the sample defined
by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.
@@ -182,6 +188,7 @@ by the sampleDurationMillis parameter. If omitted, it returns a full snapshot hi
<a name="Snapshotter+getClientSample"></a>
## `snapshotter.getClientSample(sampleDurationMillis)` ⇒ `Array`
+
Returns a sample of latest Client snapshots, with the size of the sample defined
by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history.
diff --git a/docs/api/SystemStatus.md b/docs/api/SystemStatus.md
index e3077edc2..53d8368d3 100644
--- a/docs/api/SystemStatus.md
+++ b/docs/api/SystemStatus.md
@@ -2,6 +2,7 @@
id: systemstatus
title: SystemStatus
---
+
<a name="SystemStatus"></a>
Provides a simple interface to reading system status from a [`Snapshotter`](snapshotter) instance.
@@ -24,15 +25,15 @@ returns a boolean that represents the long-term status
of the system. It considers the full snapshot history available
in the [`Snapshotter`](snapshotter) instance.
-
-* [SystemStatus](systemstatus)
- * [`new SystemStatus([options])`](#new_SystemStatus_new)
- * [`.getCurrentStatus()`](#SystemStatus+getCurrentStatus) ⇒ `Object`
- * [`.getHistoricalStatus()`](#SystemStatus+getHistoricalStatus) ⇒ `Object`
+- [SystemStatus](systemstatus)
+ - [`new SystemStatus([options])`](#new_SystemStatus_new)
+ - [`.getCurrentStatus()`](#SystemStatus+getCurrentStatus) ⇒ `Object`
+ - [`.getHistoricalStatus()`](#SystemStatus+getHistoricalStatus) ⇒ `Object`
<a name="new_SystemStatus_new"></a>
## `new SystemStatus([options])`
+
<table>
<thead>
<tr>
@@ -81,6 +82,7 @@ in the [`Snapshotter`](snapshotter) instance.
<a name="SystemStatus+getCurrentStatus"></a>
## `systemStatus.getCurrentStatus()` ⇒ `Object`
+
Returns an object with the following structure:
```javascript
@@ -99,6 +101,7 @@ and `true` otherwise.
<a name="SystemStatus+getHistoricalStatus"></a>
## `systemStatus.getHistoricalStatus()` ⇒ `Object`
+
Returns an object with the following structure:
```javascript
@@ -113,4 +116,3 @@ Returns an object with the following structure:
Where the `isSystemIdle` property is set to `false` if the system
has been overloaded in the full history of the [`Snapshotter`](snapshotter)
(which is configurable in the [`Snapshotter`](snapshotter)) and `true` otherwise.
-
diff --git a/docs/api/log.md b/docs/api/log.md
index 1a2d4a348..958d86372 100644
--- a/docs/api/log.md
+++ b/docs/api/log.md
@@ -2,6 +2,7 @@
id: log
title: utils.log
---
+
<a name="log"></a>
The log instance enables level aware logging of messages and we advise
@@ -23,6 +24,7 @@ set the appropriate level. The default log level is `INFO`, which means that
`DEBUG` messages will not be printed, unless enabled.
**Example:**
+
```
const Apify = require('apify');
const { log } = Apify.utils;
@@ -49,26 +51,27 @@ Another very useful way of setting the log level is by setting the `APIFY_LOG_LE
environment variable, such as `APIFY_LOG_LEVEL=DEBUG`. This way, no code changes
are necessary to turn on your debug messages and start debugging right away.
-
-* [`log`](#log) : `object`
- * [`.LEVELS`](#log.LEVELS) : `Object`
- * [`.setLevel(level)`](#log.setLevel)
- * [`.getLevel()`](#log.getLevel)
- * [`.debug(message, [data])`](#log.debug)
- * [`.info(message, [data])`](#log.info)
- * [`.warning(message, [data])`](#log.warning)
- * [`.error(message, [data])`](#log.error)
- * [`.exception(exception, [message], [data])`](#log.exception)
+- [`log`](#log) : `object`
+ - [`.LEVELS`](#log.LEVELS) : `Object`
+ - [`.setLevel(level)`](#log.setLevel)
+ - [`.getLevel()`](#log.getLevel)
+ - [`.debug(message, [data])`](#log.debug)
+ - [`.info(message, [data])`](#log.info)
+ - [`.warning(message, [data])`](#log.warning)
+ - [`.error(message, [data])`](#log.error)
+ - [`.exception(exception, [message], [data])`](#log.exception)
<a name="log.LEVELS"></a>
## `log.LEVELS` : `Object`
+
Map of available log levels that's useful for easy setting of appropriate log levels.
Each log level is represented internally by a number. Eg. `log.LEVELS.DEBUG === 5`.
<a name="log.setLevel"></a>
## `log.setLevel(level)`
+
Sets the log level to the given value, preventing messages from less important log levels
from being printed to the console. Use in conjunction with the `log.LEVELS` constants such as
@@ -94,6 +97,7 @@ Default log level is INFO.
<a name="log.getLevel"></a>
## `log.getLevel()`
+
Returns the currently selected logging level. This is useful for checking whether a message
will actually be printed to the console before one actually performs a resource intensive operation
to construct the message, such as querying a DB for some metadata that need to be added. If the log
@@ -102,6 +106,7 @@ level is not high enough at the moment, it doesn't make sense to execute the que
<a name="log.debug"></a>
## `log.debug(message, [data])`
+
Logs a `DEBUG` message. By default, it will not be written to the console. To see `DEBUG`
messages in the console, set the log level to `DEBUG` either using the `log.setLevel(log.LEVELS.DEBUG)`
method or using the environment variable `APIFY_LOG_LEVEL=DEBUG`. Data are stringified and appended
@@ -127,6 +132,7 @@ to the message.
<a name="log.info"></a>
## `log.info(message, [data])`
+
Logs an `INFO` message. `INFO` is the default log level so info messages will be always logged,
unless the log level is changed. Data are stringified and appended to the message.
@@ -150,6 +156,7 @@ unless the log level is changed. Data are stringified and appended to the messag
<a name="log.warning"></a>
## `log.warning(message, [data])`
+
Logs a `WARNING` level message. Data are stringified and appended to the message.
<table>
@@ -172,6 +179,7 @@ Logs a `WARNING` level message. Data are stringified and appended to the message
<a name="log.error"></a>
## `log.error(message, [data])`
+
Logs an `ERROR` message. Use this method to log error messages that are not directly connected
to an exception. For logging exceptions, use the `log.exception` method.
@@ -195,6 +203,7 @@ to an exception. For logging exceptions, use the `log.exception` method.
<a name="log.exception"></a>
## `log.exception(exception, [message], [data])`
+
Logs an `ERROR` level message with a nicely formatted exception. Note that the exception is the first parameter
here and an additional message is only optional.
diff --git a/docs/api/puppeteer.md b/docs/api/puppeteer.md
index d9d2b6de3..c088eb7d1 100644
--- a/docs/api/puppeteer.md
+++ b/docs/api/puppeteer.md
@@ -2,6 +2,7 @@
id: puppeteer
title: utils.puppeteer
---
+
<a name="puppeteer"></a>
A namespace that contains various utilities for
@@ -10,35 +11,35 @@ A namespace that contains various utilities for
**Example usage:**
```javascript
-const Apify = require('apify');
+const Apify = require("apify");
const { puppeteer } = Apify.utils;
// Open https://www.example.com in Puppeteer
const browser = await Apify.launchPuppeteer();
const page = await browser.newPage();
-await page.goto('https://www.example.com');
+await page.goto("https://www.example.com");
// Inject jQuery into a page
await puppeteer.injectJQuery(page);
```
-
-* [`puppeteer`](#puppeteer) : `object`
- * [`.enqueueLinksByClickingElements`](#puppeteer.enqueueLinksByClickingElements) ⇒ `Promise<Array<QueueOperationInfo>>`
- * [`.addInterceptRequestHandler`](#puppeteer.addInterceptRequestHandler) ⇒ `Promise`
- * [`.removeInterceptRequestHandler`](#puppeteer.removeInterceptRequestHandler) ⇒ `Promise`
- * [`.gotoExtended`](#puppeteer.gotoExtended) ⇒ `Promise<Response>`
- * [`.infiniteScroll`](#puppeteer.infiniteScroll) ⇒ `Promise`
- * [`.injectFile(page, filePath, [options])`](#puppeteer.injectFile) ⇒ `Promise`
- * [`.injectJQuery(page)`](#puppeteer.injectJQuery) ⇒ `Promise`
- * [`.injectUnderscore(page)`](#puppeteer.injectUnderscore) ⇒ `Promise`
- * [`.blockRequests(page, [options])`](#puppeteer.blockRequests) ⇒ `Promise`
- * ~~[`.cacheResponses(page, cache, responseUrlRules)`](#puppeteer.cacheResponses) ⇒ `Promise`~~
- * [`.compileScript(scriptString, context)`](#puppeteer.compileScript) ⇒ `function`
+- [`puppeteer`](#puppeteer) : `object`
+ - [`.enqueueLinksByClickingElements`](#puppeteer.enqueueLinksByClickingElements) ⇒ `Promise<Array<QueueOperationInfo>>`
+ - [`.addInterceptRequestHandler`](#puppeteer.addInterceptRequestHandler) ⇒ `Promise`
+ - [`.removeInterceptRequestHandler`](#puppeteer.removeInterceptRequestHandler) ⇒ `Promise`
+ - [`.gotoExtended`](#puppeteer.gotoExtended) ⇒ `Promise<Response>`
+ - [`.infiniteScroll`](#puppeteer.infiniteScroll) ⇒ `Promise`
+ - [`.injectFile(page, filePath, [options])`](#puppeteer.injectFile) ⇒ `Promise`
+ - [`.injectJQuery(page)`](#puppeteer.injectJQuery) ⇒ `Promise`
+ - [`.injectUnderscore(page)`](#puppeteer.injectUnderscore) ⇒ `Promise`
+ - [`.blockRequests(page, [options])`](#puppeteer.blockRequests) ⇒ `Promise`
+ - ~~[`.cacheResponses(page, cache, responseUrlRules)`](#puppeteer.cacheResponses) ⇒ `Promise`~~
+ - [`.compileScript(scriptString, context)`](#puppeteer.compileScript) ⇒ `function`
<a name="puppeteer.enqueueLinksByClickingElements"></a>
## `puppeteer.enqueueLinksByClickingElements` ⇒ `Promise<Array<QueueOperationInfo>>`
+
The function finds elements matching a specific CSS selector in a Puppeteer page,
clicks all those elements using a mouse move and a left mouse button click and intercepts
all the navigation requests that are subsequently produced by the page. The intercepted
@@ -83,7 +84,8 @@ await Apify.utils.enqueueLinksByClickingElements({
});
```
-**Returns**: `Promise<Array<QueueOperationInfo>>` - Promise that resolves to an array of [`QueueOperationInfo`](../typedefs/queueoperationinfo) objects.
+**Returns**: `Promise<Array<QueueOperationInfo>>` - Promise that resolves to an array of [`QueueOperationInfo`](../typedefs/queueoperationinfo) objects.
+
<table>
<thead>
<tr>
@@ -168,6 +170,7 @@ await Apify.utils.enqueueLinksByClickingElements({
<a name="puppeteer.addInterceptRequestHandler"></a>
## `puppeteer.addInterceptRequestHandler` ⇒ `Promise`
+
Adds request interception handler in similar to `page.on('request', handler);` but in addition to that
supports multiple parallel handlers.
@@ -181,36 +184,35 @@ override only a value of specific header.
If one the handlers calls `request.abort()` or `request.respond()` then request is not propagated further
to any of the remaining handlers.
-
**Example usage:**
```javascript
// Replace images with placeholder.
-await addInterceptRequestHandler(page, (request) => {
- if (request.resourceType() === 'image') {
+await addInterceptRequestHandler(page, request => {
+ if (request.resourceType() === "image") {
return request.respond({
statusCode: 200,
- contentType: 'image/jpeg',
- body: placeholderImageBuffer,
+ contentType: "image/jpeg",
+ body: placeholderImageBuffer
});
}
return request.continue();
});
// Abort all the scripts.
-await addInterceptRequestHandler(page, (request) => {
- if (request.resourceType() === 'script') return request.abort();
+await addInterceptRequestHandler(page, request => {
+ if (request.resourceType() === "script") return request.abort();
return request.continue();
});
// Change requests to post.
-await addInterceptRequestHandler(page, (request) => {
+await addInterceptRequestHandler(page, request => {
return request.continue({
- method: 'POST',
+ method: "POST"
});
});
-await page.goto('http://example.com');
+await page.goto("http://example.com");
```
<table>
@@ -235,6 +237,7 @@ await page.goto('http://example.com');
<a name="puppeteer.removeInterceptRequestHandler"></a>
## `puppeteer.removeInterceptRequestHandler` ⇒ `Promise`
+
Removes request interception handler for given page.
<table>
@@ -259,11 +262,12 @@ Removes request interception handler for given page.
<a name="puppeteer.gotoExtended"></a>
## `puppeteer.gotoExtended` ⇒ `Promise<Response>`
+
Extended version of Puppeteer's `page.goto()` allowing to perform requests with HTTP method other than GET,
with custom headers and POST payload. URL, method, headers and payload are taken from
request parameter that must be an instance of Apify.Request class.
-*NOTE:* In recent versions of Puppeteer using requests other than GET, overriding headers and adding payloads disables
+_NOTE:_ In recent versions of Puppeteer using requests other than GET, overriding headers and adding payloads disables
browser cache which degrades performance.
<table>
@@ -292,6 +296,7 @@ browser cache which degrades performance.
<a name="puppeteer.infiniteScroll"></a>
## `puppeteer.infiniteScroll` ⇒ `Promise`
+
Scrolls to the bottom of a page, or until it times out.
Loads dynamic content when it hits the bottom of a page, and then continues scrolling.
@@ -326,6 +331,7 @@ Loads dynamic content when it hits the bottom of a page, and then continues scro
<a name="puppeteer.injectFile"></a>
## `puppeteer.injectFile(page, filePath, [options])` ⇒ `Promise`
+
Injects a JavaScript file into a Puppeteer page.
Unlike Puppeteer's `addScriptTag` function, this function works on pages
with arbitrary Cross-Origin Resource Sharing (CORS) policies.
@@ -365,6 +371,7 @@ File contents are cached for up to 10 files to limit file system access.
<a name="puppeteer.injectJQuery"></a>
## `puppeteer.injectJQuery(page)` ⇒ `Promise`
+
Injects the <a href="https://jquery.com/" target="_blank"><code>jQuery</code></a> library into a Puppeteer page.
jQuery is often useful for various web scraping and crawling tasks.
For example, it can help extract text from HTML elements using CSS selectors.
@@ -376,15 +383,16 @@ This can affect functionality of page's scripts.
The injected jQuery will survive page navigations and reloads.
**Example usage:**
+
```javascript
await Apify.utils.puppeteer.injectJQuery(page);
const title = await page.evaluate(() => {
- return $('head title').text();
+ return $("head title").text();
});
```
Note that `injectJQuery()` does not affect the Puppeteer's
-<a href="https://pptr.dev/#?product=Puppeteer&show=api-pageselector" target="_blank"><code>Page.$()</code></a>
+<a href="https://pptr.dev/#?product=Puppeteer&show=api-pageselector" target="_blank"><code>Page.\$()</code></a>
function in any way.
<table>
@@ -404,6 +412,7 @@ function in any way.
<a name="puppeteer.injectUnderscore"></a>
## `puppeteer.injectUnderscore(page)` ⇒ `Promise`
+
Injects the <a href="https://underscorejs.org/" target="_blank"><code>Underscore.js</code></a> library into a Puppeteer page.
Beware that the injected Underscore object will be set to the `window._` variable and thus it might cause conflicts with
@@ -413,10 +422,11 @@ This can affect functionality of page's scripts.
The injected Underscore will survive page navigations and reloads.
**Example usage:**
+
```javascript
await Apify.utils.puppeteer.injectUnderscore(page);
const escapedHtml = await page.evaluate(() => {
- return _.escape('<h1>Hello</h1>');
+ return _.escape("<h1>Hello</h1>");
});
```
@@ -437,6 +447,7 @@ const escapedHtml = await page.evaluate(() => {
<a name="puppeteer.blockRequests"></a>
## `puppeteer.blockRequests(page, [options])` ⇒ `Promise`
+
Forces the Puppeteer browser tab to block loading URLs that match a provided pattern.
This is useful to speed up crawling of websites, since it reduces the amount
of data that needs to be downloaded from the web, but it may break some websites
@@ -460,18 +471,19 @@ but it does not provide the extra benefits of request interception.
The function will never block main document loads and their respective redirects.
**Example usage**
+
```javascript
-const Apify = require('apify');
+const Apify = require("apify");
const browser = await Apify.launchPuppeteer();
const page = await browser.newPage();
// Block all requests to URLs that include `adsbygoogle.js` and also all defaults.
await Apify.utils.puppeteer.blockRequests(page, {
- extraUrlPatterns: ['adsbygoogle.js'],
+ extraUrlPatterns: ["adsbygoogle.js"]
});
-await page.goto('https://cnn.com');
+await page.goto("https://cnn.com");
```
<table>
@@ -508,14 +520,15 @@ await page.goto('https://cnn.com');
<a name="puppeteer.cacheResponses"></a>
## ~~`puppeteer.cacheResponses(page, cache, responseUrlRules)` ⇒ `Promise`~~
-***Deprecated***
-*NOTE:* In recent versions of Puppeteer using this function entirely disables browser cache which resolves in sub-optimal
+**_Deprecated_**
+
+_NOTE:_ In recent versions of Puppeteer using this function entirely disables browser cache which resolves in sub-optimal
performance. Until this resolves, we suggest just relying on the in-browser cache unless absolutely necessary.
Enables caching of intercepted responses into a provided object. Automatically enables request interception in Puppeteer.
-*IMPORTANT*: Caching responses stores them to memory, so too loose rules could cause memory leaks for longer running crawlers.
- This issue should be resolved or atleast mitigated in future iterations of this feature.
+_IMPORTANT_: Caching responses stores them to memory, so too loose rules could cause memory leaks for longer running crawlers.
+This issue should be resolved or atleast mitigated in future iterations of this feature.
<table>
<thead>
@@ -545,14 +558,17 @@ Enables caching of intercepted responses into a provided object. Automatically e
<a name="puppeteer.compileScript"></a>
## `puppeteer.compileScript(scriptString, context)` ⇒ `function`
+
Compiles a Puppeteer script into an async function that may be executed at any time
by providing it with the following object:
+
```
{
page: Page,
request: Request,
}
```
+
Where `page` is a Puppeteer <a href="https://pptr.dev/#?product=Puppeteer&show=api-class-page" target="_blank"><code>Page</code></a>
and `request` is a [`Request`](request).
@@ -570,7 +586,8 @@ Custom context may also be provided using the `context` parameter. To improve se
make sure to only pass the really necessary objects to the context. Preferably making
secured copies beforehand.
-**Returns**: `function` - `async ({ page, request }) => { scriptString }`
+**Returns**: `function` - `async ({ page, request }) => { scriptString }`
+
<table>
<thead>
<tr>
diff --git a/docs/api/social.md b/docs/api/social.md
index 9b3499ec3..596581e8b 100644
--- a/docs/api/social.md
+++ b/docs/api/social.md
@@ -2,6 +2,7 @@
id: social
title: utils.social
---
+
<a name="social"></a>
A namespace that contains various utilities to help you extract social handles
@@ -10,34 +11,37 @@ from text, URLs and and HTML documents.
**Example usage:**
```javascript
-const Apify = require('apify');
-
-const emails = Apify.utils.social.emailsFromText('[email protected] [email protected]');
-```
-
-
-* [`social`](#social) : `object`
- * [`.LINKEDIN_REGEX`](#social.LINKEDIN_REGEX) : `RegExp`
- * [`.LINKEDIN_REGEX_GLOBAL`](#social.LINKEDIN_REGEX_GLOBAL) : `RegExp`
- * [`.INSTAGRAM_REGEX`](#social.INSTAGRAM_REGEX) : `RegExp`
- * [`.INSTAGRAM_REGEX_GLOBAL`](#social.INSTAGRAM_REGEX_GLOBAL) : `RegExp`
- * [`.TWITTER_REGEX`](#social.TWITTER_REGEX) : `RegExp`
- * [`.TWITTER_REGEX_GLOBAL`](#social.TWITTER_REGEX_GLOBAL) : `RegExp`
- * [`.FACEBOOK_REGEX`](#social.FACEBOOK_REGEX) : `RegExp`
- * [`.FACEBOOK_REGEX_GLOBAL`](#social.FACEBOOK_REGEX_GLOBAL) : `RegExp`
- * [`.EMAIL_REGEX`](#social.EMAIL_REGEX) : `RegExp`
- * [`.EMAIL_REGEX_GLOBAL`](#social.EMAIL_REGEX_GLOBAL) : `RegExp`
- * [`.emailsFromText(text)`](#social.emailsFromText) ⇒ `Array<String>`
- * [`.emailsFromUrls(urls)`](#social.emailsFromUrls) ⇒ `Array<String>`
- * [`.phonesFromText(text)`](#social.phonesFromText) ⇒ `Array<String>`
- * [`.phonesFromUrls(urls)`](#social.phonesFromUrls) ⇒ `Array<String>`
- * [`.parseHandlesFromHtml(html, data)`](#social.parseHandlesFromHtml) ⇒ `*`
+const Apify = require("apify");
+
+const emails = Apify.utils.social.emailsFromText(
+);
+```
+
+- [`social`](#social) : `object`
+ - [`.LINKEDIN_REGEX`](#social.LINKEDIN_REGEX) : `RegExp`
+ - [`.LINKEDIN_REGEX_GLOBAL`](#social.LINKEDIN_REGEX_GLOBAL) : `RegExp`
+ - [`.INSTAGRAM_REGEX`](#social.INSTAGRAM_REGEX) : `RegExp`
+ - [`.INSTAGRAM_REGEX_GLOBAL`](#social.INSTAGRAM_REGEX_GLOBAL) : `RegExp`
+ - [`.TWITTER_REGEX`](#social.TWITTER_REGEX) : `RegExp`
+ - [`.TWITTER_REGEX_GLOBAL`](#social.TWITTER_REGEX_GLOBAL) : `RegExp`
+ - [`.FACEBOOK_REGEX`](#social.FACEBOOK_REGEX) : `RegExp`
+ - [`.FACEBOOK_REGEX_GLOBAL`](#social.FACEBOOK_REGEX_GLOBAL) : `RegExp`
+ - [`.EMAIL_REGEX`](#social.EMAIL_REGEX) : `RegExp`
+ - [`.EMAIL_REGEX_GLOBAL`](#social.EMAIL_REGEX_GLOBAL) : `RegExp`
+ - [`.emailsFromText(text)`](#social.emailsFromText) ⇒ `Array<String>`
+ - [`.emailsFromUrls(urls)`](#social.emailsFromUrls) ⇒ `Array<String>`
+ - [`.phonesFromText(text)`](#social.phonesFromText) ⇒ `Array<String>`
+ - [`.phonesFromUrls(urls)`](#social.phonesFromUrls) ⇒ `Array<String>`
+ - [`.parseHandlesFromHtml(html, data)`](#social.parseHandlesFromHtml) ⇒ `*`
<a name="social.LINKEDIN_REGEX"></a>
## `social.LINKEDIN_REGEX` : `RegExp`
+
Regular expression to exactly match a single LinkedIn profile URL.
It has the following form: `/^...$/i` and matches URLs such as:
+
```
https://www.linkedin.com/in/alan-turing
en.linkedin.com/in/alan-turing
@@ -46,11 +50,13 @@ linkedin.com/in/alan-turing
The regular expression does NOT match URLs with additional
subdirectories or query parameters, such as:
+
```
https://www.linkedin.com/in/linus-torvalds/latest-activity
```
Example usage:
+
```
if (Apify.utils.social.LINKEDIN_REGEX.test('https://www.linkedin.com/in/alan-turing')) {
console.log('Match!');
@@ -60,8 +66,10 @@ if (Apify.utils.social.LINKEDIN_REGEX.test('https://www.linkedin.com/in/alan-tur
<a name="social.LINKEDIN_REGEX_GLOBAL"></a>
## `social.LINKEDIN_REGEX_GLOBAL` : `RegExp`
+
Regular expression to find multiple LinkedIn profile URLs in a text or HTML.
It has the following form: `/.../ig` and matches URLs such as:
+
```
https://www.linkedin.com/in/alan-turing
en.linkedin.com/in/alan-turing
@@ -70,15 +78,19 @@ linkedin.com/in/alan-turing
If the profile URL contains subdirectories or query parameters, the regular expression
extracts just the base part of the profile URL. For example, from text such as:
+
```
https://www.linkedin.com/in/linus-torvalds/latest-activity
```
+
the expression extracts just the following base URL:
+
```
https://www.linkedin.com/in/linus-torvalds
```
Example usage:
+
```
const matches = text.match(Apify.utils.social.LINKEDIN_REGEX_GLOBAL);
if (matches) console.log(`${matches.length} LinkedIn profiles found!`);
@@ -87,8 +99,10 @@ if (matches) console.log(`${matches.length} LinkedIn profiles found!`);
<a name="social.INSTAGRAM_REGEX"></a>
## `social.INSTAGRAM_REGEX` : `RegExp`
+
Regular expression to exactly match a single Instagram profile URL.
It has the following form: `/^...$/i` and matches URLs such as:
+
```
https://www.instagram.com/old_prague
www.instagram.com/old_prague/
@@ -97,11 +111,13 @@ instagr.am/old_prague
The regular expression does NOT match URLs with additional
subdirectories or query parameters, such as:
+
```
https://www.instagram.com/cristiano/followers
```
Example usage:
+
```
if (Apify.utils.social.INSTAGRAM_REGEX_STRING.test('https://www.instagram.com/old_prague')) {
console.log('Match!');
@@ -111,8 +127,10 @@ if (Apify.utils.social.INSTAGRAM_REGEX_STRING.test('https://www.instagram.com/ol
<a name="social.INSTAGRAM_REGEX_GLOBAL"></a>
## `social.INSTAGRAM_REGEX_GLOBAL` : `RegExp`
+
Regular expression to find multiple Instagram profile URLs in a text or HTML.
It has the following form: `/.../ig` and matches URLs such as:
+
```
https://www.instagram.com/old_prague
www.instagram.com/old_prague/
@@ -121,15 +139,19 @@ instagr.am/old_prague
If the profile URL contains subdirectories or query parameters, the regular expression
extracts just the base part of the profile URL. For example, from text such as:
+
```
https://www.instagram.com/cristiano/followers
```
+
the expression extracts just the following base URL:
+
```
https://www.instagram.com/cristiano
```
Example usage:
+
```
const matches = text.match(Apify.utils.social.INSTAGRAM_REGEX_GLOBAL);
if (matches) console.log(`${matches.length} Instagram profiles found!`);
@@ -138,8 +160,10 @@ if (matches) console.log(`${matches.length} Instagram profiles found!`);
<a name="social.TWITTER_REGEX"></a>
## `social.TWITTER_REGEX` : `RegExp`
+
Regular expression to exactly match a single Twitter profile URL.
It has the following form: `/^...$/i` and matches URLs such as:
+
```
https://www.twitter.com/apify
twitter.com/apify
@@ -147,11 +171,13 @@ twitter.com/apify
The regular expression does NOT match URLs with additional
subdirectories or query parameters, such as:
+
```
https://www.twitter.com/realdonaldtrump/following
```
Example usage:
+
```
if (Apify.utils.social.TWITTER_REGEX_STRING.test('https://www.twitter.com/apify')) {
console.log('Match!');
@@ -161,8 +187,10 @@ if (Apify.utils.social.TWITTER_REGEX_STRING.test('https://www.twitter.com/apify'
<a name="social.TWITTER_REGEX_GLOBAL"></a>
## `social.TWITTER_REGEX_GLOBAL` : `RegExp`
+
Regular expression to find multiple Twitter profile URLs in a text or HTML.
It has the following form: `/.../ig` and matches URLs such as:
+
```
https://www.twitter.com/apify
twitter.com/apify
@@ -170,15 +198,19 @@ twitter.com/apify
If the profile URL contains subdirectories or query parameters, the regular expression
extracts just the base part of the profile URL. For example, from text such as:
+
```
https://www.twitter.com/realdonaldtrump/following
```
+
the expression extracts only the following base URL:
+
```
https://www.twitter.com/realdonaldtrump
```
Example usage:
+
```
const matches = text.match(Apify.utils.social.TWITTER_REGEX_STRING);
if (matches) console.log(`${matches.length} Twitter profiles found!`);
@@ -187,8 +219,10 @@ if (matches) console.log(`${matches.length} Twitter profiles found!`);
<a name="social.FACEBOOK_REGEX"></a>
## `social.FACEBOOK_REGEX` : `RegExp`
+
Regular expression to exactly match a single Facebook profile URL.
It has the following form: `/^...$/i` and matches URLs such as:
+
```
https://www.facebook.com/apifytech
facebook.com/apifytech
@@ -198,11 +232,13 @@ https://www.facebook.com/profile.php?id=123456789
The regular expression does NOT match URLs with additional
subdirectories or query parameters, such as:
+
```
https://www.facebook.com/apifytech/photos
```
Example usage:
+
```
if (Apify.utils.social.FACEBOOK_REGEX_STRING.test('https://www.facebook.com/apifytech')) {
console.log('Match!');
@@ -212,8 +248,10 @@ if (Apify.utils.social.FACEBOOK_REGEX_STRING.test('https://www.facebook.com/apif
<a name="social.FACEBOOK_REGEX_GLOBAL"></a>
## `social.FACEBOOK_REGEX_GLOBAL` : `RegExp`
+
Regular expression to find multiple Facebook profile URLs in a text or HTML.
It has the following form: `/.../ig` and matches URLs such as:
+
```
https://www.facebook.com/apifytech
facebook.com/apifytech
@@ -222,15 +260,19 @@ fb.com/apifytech
If the profile URL contains subdirectories or query parameters, the regular expression
extracts just the base part of the profile URL. For example, from text such as:
+
```
https://www.facebook.com/apifytech/photos
```
+
the expression extracts only the following base URL:
+
```
https://www.facebook.com/apifytech
```
Example usage:
+
```
const matches = text.match(Apify.utils.social.FACEBOOK_REGEX_GLOBAL);
if (matches) console.log(`${matches.length} Facebook profiles found!`);
@@ -239,23 +281,27 @@ if (matches) console.log(`${matches.length} Facebook profiles found!`);
<a name="social.EMAIL_REGEX"></a>
## `social.EMAIL_REGEX` : `RegExp`
+
Regular expression to exactly match a single email address.
It has the following form: `/^...$/i`.
<a name="social.EMAIL_REGEX_GLOBAL"></a>
## `social.EMAIL_REGEX_GLOBAL` : `RegExp`
+
Regular expression to find multiple email addresses in a text.
It has the following form: `/.../ig`.
<a name="social.emailsFromText"></a>
## `social.emailsFromText(text)` ⇒ `Array<String>`
+
The function extracts email addresses from a plain text.
Note that the function preserves the order of emails and keep duplicates.
**Returns**: `Array<String>` - Array of emails addresses found.
-If no emails are found, the function returns an empty array.
+If no emails are found, the function returns an empty array.
+
<table>
<thead>
<tr>
@@ -273,12 +319,14 @@ If no emails are found, the function returns an empty array.
<a name="social.emailsFromUrls"></a>
## `social.emailsFromUrls(urls)` ⇒ `Array<String>`
+
The function extracts email addresses from a list of URLs.
Basically it looks for all `mailto:` URLs and returns valid email addresses from them.
Note that the function preserves the order of emails and keep duplicates.
**Returns**: `Array<String>` - Array of emails addresses found.
-If no emails are found, the function returns an empty array.
+If no emails are found, the function returns an empty array.
+
<table>
<thead>
<tr>
@@ -296,12 +344,14 @@ If no emails are found, the function returns an empty array.
<a name="social.phonesFromText"></a>
## `social.phonesFromText(text)` ⇒ `Array<String>`
+
The function attempts to extract phone numbers from a text. Please note that
the results might not be accurate, since phone numbers appear in a large variety of formats and conventions.
If you encounter some problems, please [file an issue](https://github.com/apifytech/apify-js/issues).
**Returns**: `Array<String>` - Array of phone numbers found.
-If no phone numbers are found, the function returns an empty array.
+If no phone numbers are found, the function returns an empty array.
+
<table>
<thead>
<tr>
@@ -319,11 +369,13 @@ If no phone numbers are found, the function returns an empty array.
<a name="social.phonesFromUrls"></a>
## `social.phonesFromUrls(urls)` ⇒ `Array<String>`
+
Finds phone number links in an array of URLs and extracts the phone numbers from them.
Note that the phone number links look like `tel://123456789`, `tel:/123456789` or `tel:123456789`.
**Returns**: `Array<String>` - Array of phone numbers found.
-If no phone numbers are found, the function returns an empty array.
+If no phone numbers are found, the function returns an empty array.
+
<table>
<thead>
<tr>
@@ -341,11 +393,13 @@ If no phone numbers are found, the function returns an empty array.
<a name="social.parseHandlesFromHtml"></a>
## `social.parseHandlesFromHtml(html, data)` ⇒ `*`
+
The function attempts to extract emails, phone numbers and social profile URLs from a HTML document,
specifically LinkedIn, Twitter, Instagram and Facebook profile URLs.
The function removes duplicates from the resulting arrays and sorts the items alphabetically.
The result of the function is an object with the following structure:
+
```
{
emails: String[],
@@ -364,20 +418,22 @@ and potentially other sources with high certainty, while `phonesUncertain` conta
extracted from the plain text, which might be very inaccurate.
**Example usage:**
+
```javascript
-const Apify = require('apify');
+const Apify = require("apify");
const browser = await Apify.launchPuppeteer();
const page = await browser.newPage();
-await page.goto('http://www.example.com');
+await page.goto("http://www.example.com");
const html = await page.content();
const result = Apify.utils.social.parseHandlesFromHtml(html);
-console.log('Social handles:');
+console.log("Social handles:");
console.dir(result);
```
-**Returns**: `*` - An object with the social handles.
+**Returns**: `*` - An object with the social handles.
+
<table>
<thead>
<tr>
diff --git a/docs/api/utils.md b/docs/api/utils.md
index 5c617d274..9ee8d8cbc 100644
--- a/docs/api/utils.md
+++ b/docs/api/utils.md
@@ -2,6 +2,7 @@
id: utils
title: utils
---
+
<a name="utils"></a>
A namespace that contains various utilities.
@@ -17,21 +18,21 @@ const Apify = require('apify');
await Apify.utils.sleep(1500);
```
-
-* [`utils`](#utils) : `object`
- * [`.enqueueLinks`](#utils.enqueueLinks) ⇒ `Promise<Array<QueueOperationInfo>>`
- * [`.sleep`](#utils.sleep) ⇒ `Promise`
- * [`.URL_NO_COMMAS_REGEX`](#utils.URL_NO_COMMAS_REGEX)
- * [`.URL_WITH_COMMAS_REGEX`](#utils.URL_WITH_COMMAS_REGEX)
- * [`.isDocker()`](#utils.isDocker) ⇒ `Promise`
- * [`.downloadListOfUrls(options)`](#utils.downloadListOfUrls) ⇒ `Promise<Array<String>>`
- * [`.extractUrls(options)`](#utils.extractUrls) ⇒ `Array<String>`
- * [`.getRandomUserAgent()`](#utils.getRandomUserAgent) ⇒ `String`
- * [`.htmlToText(html)`](#utils.htmlToText) ⇒ `String`
+- [`utils`](#utils) : `object`
+ - [`.enqueueLinks`](#utils.enqueueLinks) ⇒ `Promise<Array<QueueOperationInfo>>`
+ - [`.sleep`](#utils.sleep) ⇒ `Promise`
+ - [`.URL_NO_COMMAS_REGEX`](#utils.URL_NO_COMMAS_REGEX)
+ - [`.URL_WITH_COMMAS_REGEX`](#utils.URL_WITH_COMMAS_REGEX)
+ - [`.isDocker()`](#utils.isDocker) ⇒ `Promise`
+ - [`.downloadListOfUrls(options)`](#utils.downloadListOfUrls) ⇒ `Promise<Array<String>>`
+ - [`.extractUrls(options)`](#utils.extractUrls) ⇒ `Array<String>`
+ - [`.getRandomUserAgent()`](#utils.getRandomUserAgent) ⇒ `String`
+ - [`.htmlToText(html)`](#utils.htmlToText) ⇒ `String`
<a name="utils.enqueueLinks"></a>
## `utils.enqueueLinks` ⇒ `Promise<Array<QueueOperationInfo>>`
+
The function finds elements matching a specific CSS selector (HTML anchor (`<a>`) by default)
either in a Puppeteer page, or in a Cheerio object (parsed HTML),
and enqueues the URLs in their `href` attributes to the provided [`RequestQueue`](requestqueue).
@@ -45,24 +46,25 @@ and override settings of the enqueued [`Request`](request) objects.
**Example usage**
```javascript
-const Apify = require('apify');
+const Apify = require("apify");
const browser = await Apify.launchPuppeteer();
-const page = await browser.goto('https://www.example.com');
+const page = await browser.goto("https://www.example.com");
const requestQueue = await Apify.openRequestQueue();
await Apify.utils.enqueueLinks({
- page,
- requestQueue,
- selector: 'a.product-detail',
- pseudoUrls: [
- 'https://www.example.com/handbags/[.*]',
- 'https://www.example.com/purses/[.*]'
- ],
+ page,
+ requestQueue,
+ selector: "a.product-detail",
+ pseudoUrls: [
+ "https://www.example.com/handbags/[.*]",
+ "https://www.example.com/purses/[.*]"
+ ]
});
```
-**Returns**: `Promise<Array<QueueOperationInfo>>` - Promise that resolves to an array of [`QueueOperationInfo`](../typedefs/queueoperationinfo) objects.
+**Returns**: `Promise<Array<QueueOperationInfo>>` - Promise that resolves to an array of [`QueueOperationInfo`](../typedefs/queueoperationinfo) objects.
+
<table>
<thead>
<tr>
@@ -130,6 +132,7 @@ await Apify.utils.enqueueLinks({
<a name="utils.sleep"></a>
## `utils.sleep` ⇒ `Promise`
+
Returns a `Promise` that resolves after a specific period of time. This is useful to implement waiting
in your code, e.g. to prevent overloading of target website or to avoid bot detection.
@@ -161,23 +164,27 @@ await Apify.utils.sleep(1500);
<a name="utils.URL_NO_COMMAS_REGEX"></a>
## `utils.URL_NO_COMMAS_REGEX`
+
Default regular expression to match URLs in a string that may be plain text, JSON, CSV or other. It supports common URL characters
and does not support URLs containing commas or spaces. The URLs also may contain Unicode letters (not symbols).
<a name="utils.URL_WITH_COMMAS_REGEX"></a>
## `utils.URL_WITH_COMMAS_REGEX`
+
Regular expression that, in addition to the default regular expression `URL_NO_COMMAS_REGEX`, supports matching commas in URL path and query.
Note, however, that this may prevent parsing URLs from comma delimited lists, or the URLs may become malformed.
<a name="utils.isDocker"></a>
## `utils.isDocker()` ⇒ `Promise`
+
Returns a `Promise` that resolves to true if the code is running in a Docker container.
<a name="utils.downloadListOfUrls"></a>
## `utils.downloadListOfUrls(options)` ⇒ `Promise<Array<String>>`
+
Returns a promise that resolves to an array of urls parsed from the resource available at the provided url.
Optionally, custom regular expression and encoding may be provided.
@@ -213,6 +220,7 @@ Optionally, custom regular expression and encoding may be provided.
<a name="utils.extractUrls"></a>
## `utils.extractUrls(options)` ⇒ `Array<String>`
+
Collects all URLs in an arbitrary string to an array, optionally using a custom regular expression.
<table>
@@ -239,11 +247,13 @@ Collects all URLs in an arbitrary string to an array, optionally using a custom
<a name="utils.getRandomUserAgent"></a>
## `utils.getRandomUserAgent()` ⇒ `String`
+
Returns a randomly selected User-Agent header out of a list of the most common headers.
<a name="utils.htmlToText"></a>
## `utils.htmlToText(html)` ⇒ `String`
+
The function converts a HTML document to a plain text.
The plain text generated by the function is similar to a text captured
@@ -253,8 +263,9 @@ However, it attempts to generate newlines and whitespaces in and around HTML ele
to avoid merging distinct parts of text and thus enable extraction of data from the text (e.g. phone numbers).
**Example usage**
+
```javascript
-const text = htmlToText('<html><body>Some text</body></html>');
+const text = htmlToText("<html><body>Some text</body></html>");
console.log(text);
```
@@ -264,12 +275,13 @@ an existing Cheerio object to the function instead of the HTML text. The HTML sh
with the `decodeEntities` option set to `true`. For example:
```javascript
-const cheerio = require('cheerio');
-const html = '<html><body>Some text</body></html>';
+const cheerio = require("cheerio");
+const html = "<html><body>Some text</body></html>";
const text = htmlToText(cheerio.load(html, { decodeEntities: true }));
```
-**Returns**: `String` - Plain text
+**Returns**: `String` - Plain text
+
<table>
<thead>
<tr>
diff --git a/docs/examples/BasicCrawler.md b/docs/examples/BasicCrawler.md
index f99f72092..d2b798887 100644
--- a/docs/examples/BasicCrawler.md
+++ b/docs/examples/BasicCrawler.md
@@ -14,9 +14,10 @@ In local configuration, the data will be stored as JSON files in `./apify_storag
To run this example on the Apify Platform, select the `Node.js 8 on Alpine Linux (apify/actor-node-basic)` base image
on the source tab of your actor configuration.
+
```javascript
-const Apify = require('apify');
-const requestPromise = require('request-promise');
+const Apify = require("apify");
+const requestPromise = require("request-promise");
// Apify.main() function wraps the crawler logic (it is optional).
Apify.main(async () => {
@@ -24,18 +25,17 @@ Apify.main(async () => {
// a list of URLs to crawl. Here we use just a few hard-coded URLs.
const requestList = new Apify.RequestList({
sources: [
- { url: 'http://www.google.com/' },
- { url: 'http://www.example.com/' },
- { url: 'http://www.bing.com/' },
- { url: 'http://www.wikipedia.com/' },
- ],
+ { url: "http://www.google.com/" },
+ { url: "http://www.example.com/" },
+ { url: "http://www.bing.com/" },
+ { url: "http://www.wikipedia.com/" }
+ ]
});
await requestList.initialize();
// Create a BasicCrawler - the simplest crawler that enables
// users to implement the crawling logic themselves.
const crawler = new Apify.BasicCrawler({
-
// Let the crawler fetch URLs from our list.
requestList,
@@ -51,14 +51,14 @@ Apify.main(async () => {
// Store the HTML and URL to the default dataset.
await Apify.pushData({
url: request.url,
- html,
+ html
});
- },
+ }
});
// Run the crawler and wait for it to finish.
await crawler.run();
- console.log('Crawler finished.');
+ console.log("Crawler finished.");
});
-```
\ No newline at end of file
+```
diff --git a/docs/examples/CallActor.md b/docs/examples/CallActor.md
index 734ff1852..3087a1c60 100644
--- a/docs/examples/CallActor.md
+++ b/docs/examples/CallActor.md
@@ -18,21 +18,25 @@ morning.
To run this example on the Apify Platform, select the `Node.js 8 + Chrome on Debian (apify/actor-node-chrome)` base image
on the source tab of your actor configuration.
+
```javascript
-const Apify = require('apify');
+const Apify = require("apify");
Apify.main(async () => {
// Launch the web browser.
const browser = await Apify.launchPuppeteer();
- console.log('Obtaining email address...');
+ console.log("Obtaining email address...");
const user = await Apify.client.users.getUser();
// Load Kraken.com charts and get last traded price of BTC
- console.log('Extracting data from kraken.com...');
+ console.log("Extracting data from kraken.com...");
const page = await browser.newPage();
- await page.goto('https://www.kraken.com/charts');
- const tradedPricesHtml = await page.$eval('#ticker-top ul', el => el.outerHTML);
+ await page.goto("https://www.kraken.com/charts");
+ const tradedPricesHtml = await page.$eval(
+ "#ticker-top ul",
+ el => el.outerHTML
+ );
// Send prices to your email. For that, you can use an actor we already
// have available on the platform under the name: apify/send-mail.
@@ -40,12 +44,12 @@ Apify.main(async () => {
// desired input. You can find the required input parameters by checking
// the actor's documentation page: https://apify.com/apify/send-mail
console.log(`Sending email to ${user.email}...`);
- await Apify.call('apify/send-mail', {
+ await Apify.call("apify/send-mail", {
to: user.email,
- subject: 'Kraken.com BTC',
- html: `<h1>Kraken.com BTC</h1>${tradedPricesHtml}`,
+ subject: "Kraken.com BTC",
+ html: `<h1>Kraken.com BTC</h1>${tradedPricesHtml}`
});
- console.log('Email sent. Good luck!');
+ console.log("Email sent. Good luck!");
});
-```
\ No newline at end of file
+```
diff --git a/docs/examples/CheerioCrawler.md b/docs/examples/CheerioCrawler.md
index f570734b5..68e240f47 100644
--- a/docs/examples/CheerioCrawler.md
+++ b/docs/examples/CheerioCrawler.md
@@ -10,8 +10,9 @@ and extract some data from it: the page title and all H1 tags.
To run this example on the Apify Platform, select the `Node.js 8 on Alpine Linux (apify/actor-node-basic)` base image
on the source tab of your actor configuration.
+
```javascript
-const Apify = require('apify');
+const Apify = require("apify");
// Apify.utils contains various utilities, e.g. for logging.
// Here we turn off the logging of unimportant messages.
@@ -19,14 +20,15 @@ const { log } = Apify.utils;
log.setLevel(log.LEVELS.WARNING);
// A link to a list of Fortune 500 companies' websites available on GitHub.
-const CSV_LINK = 'https://gist.githubusercontent.com/hrbrmstr/ae574201af3de035c684/raw/f1000.csv';
+const CSV_LINK =
+ "https://gist.githubusercontent.com/hrbrmstr/ae574201af3de035c684/raw/f1000.csv";
// Apify.main() function wraps the crawler logic (it is optional).
Apify.main(async () => {
// Create an instance of the RequestList class that contains a list of URLs to crawl.
// Here we download and parse the list of URLs from an external file.
const requestList = new Apify.RequestList({
- sources: [{ requestsFromUrl: CSV_LINK }],
+ sources: [{ requestsFromUrl: CSV_LINK }]
});
await requestList.initialize();
@@ -57,11 +59,11 @@ Apify.main(async () => {
console.log(`Processing ${request.url}...`);
// Extract data from the page using cheerio.
- const title = $('title').text();
+ const title = $("title").text();
const h1texts = [];
- $('h1').each((index, el) => {
+ $("h1").each((index, el) => {
h1texts.push({
- text: $(el).text(),
+ text: $(el).text()
});
});
@@ -71,19 +73,19 @@ Apify.main(async () => {
url: request.url,
title,
h1texts,
- html,
+ html
});
},
// This function is called if the page processing failed more than maxRequestRetries+1 times.
handleFailedRequestFunction: async ({ request }) => {
console.log(`Request ${request.url} failed twice.`);
- },
+ }
});
// Run the crawler and wait for it to finish.
await crawler.run();
- console.log('Crawler finished.');
+ console.log("Crawler finished.");
});
-```
\ No newline at end of file
+```
diff --git a/docs/examples/HelloWorld.md b/docs/examples/HelloWorld.md
index 5ef4f5270..41ddc60ce 100644
--- a/docs/examples/HelloWorld.md
+++ b/docs/examples/HelloWorld.md
@@ -7,25 +7,31 @@ Run the following example to perform a recursive crawl of a website using Puppet
To run this example on the Apify Platform, select the `Node.js 8 + Chrome on Debian (apify/actor-node-chrome)` base image
on the source tab of your actor configuration.
+
```javascript
-const Apify = require('apify');
+const Apify = require("apify");
Apify.main(async () => {
const requestQueue = await Apify.openRequestQueue();
- await requestQueue.addRequest({ url: 'https://www.iana.org/' });
- const pseudoUrls = [new Apify.PseudoUrl('https://www.iana.org/[.*]')];
+ await requestQueue.addRequest({ url: "https://www.iana.org/" });
+ const pseudoUrls = [new Apify.PseudoUrl("https://www.iana.org/[.*]")];
const crawler = new Apify.PuppeteerCrawler({
requestQueue,
handlePageFunction: async ({ request, page }) => {
const title = await page.title();
console.log(`Title of ${request.url}: ${title}`);
- await Apify.utils.enqueueLinks({ page, selector: 'a', pseudoUrls, requestQueue });
+ await Apify.utils.enqueueLinks({
+ page,
+ selector: "a",
+ pseudoUrls,
+ requestQueue
+ });
},
maxRequestsPerCrawl: 100,
- maxConcurrency: 10,
+ maxConcurrency: 10
});
await crawler.run();
});
-```
\ No newline at end of file
+```
diff --git a/docs/examples/PuppeteerCrawler.md b/docs/examples/PuppeteerCrawler.md
index f2b348500..1810d48fc 100644
--- a/docs/examples/PuppeteerCrawler.md
+++ b/docs/examples/PuppeteerCrawler.md
@@ -12,14 +12,15 @@ The results are stored to the default dataset. In local configuration, the resul
To run this example on the Apify Platform, select the `Node.js 8 + Chrome on Debian (apify/actor-node-chrome)` base image
on the source tab of your actor configuration.
+
```javascript
-const Apify = require('apify');
+const Apify = require("apify");
Apify.main(async () => {
// Apify.openRequestQueue() is a factory to get a preconfigured RequestQueue instance.
// We add our first request to it - the initial page the crawler will visit.
const requestQueue = await Apify.openRequestQueue();
- await requestQueue.addRequest({ url: 'https://news.ycombinator.com/' });
+ await requestQueue.addRequest({ url: "https://news.ycombinator.com/" });
// Create an instance of the PuppeteerCrawler class - a crawler
// that automatically loads the URLs in headless Chrome / Puppeteer.
@@ -45,21 +46,21 @@ Apify.main(async () => {
console.log(`Processing ${request.url}...`);
// A function to be evaluated by Puppeteer within the browser context.
- const pageFunction = ($posts) => {
+ const pageFunction = $posts => {
const data = [];
// We're getting the title, rank and URL of each post on Hacker News.
- $posts.forEach(($post) => {
+ $posts.forEach($post => {
data.push({
- title: $post.querySelector('.title a').innerText,
- rank: $post.querySelector('.rank').innerText,
- href: $post.querySelector('.title a').href,
+ title: $post.querySelector(".title a").innerText,
+ rank: $post.querySelector(".rank").innerText,
+ href: $post.querySelector(".title a").href
});
});
return data;
};
- const data = await page.$$eval('.athing', pageFunction);
+ const data = await page.$$eval(".athing", pageFunction);
// Store the results to the default dataset.
await Apify.pushData(data);
@@ -68,24 +69,25 @@ Apify.main(async () => {
const infos = await Apify.utils.enqueueLinks({
page,
requestQueue,
- selector: '.morelink',
+ selector: ".morelink"
});
- if (infos.length === 0) console.log(`${request.url} is the last page!`);
+ if (infos.length === 0)
+ console.log(`${request.url} is the last page!`);
},
// This function is called if the page processing failed more than maxRequestRetries+1 times.
handleFailedRequestFunction: async ({ request }) => {
console.log(`Request ${request.url} failed too many times`);
await Apify.pushData({
- '#debug': Apify.utils.createRequestDebugInfo(request),
+ "#debug": Apify.utils.createRequestDebugInfo(request)
});
- },
+ }
});
// Run the crawler and wait for it to finish.
await crawler.run();
- console.log('Crawler finished.');
+ console.log("Crawler finished.");
});
-```
\ No newline at end of file
+```
diff --git a/docs/examples/PuppeteerSitemap.md b/docs/examples/PuppeteerSitemap.md
index e7f635cc4..8846dc2e1 100644
--- a/docs/examples/PuppeteerSitemap.md
+++ b/docs/examples/PuppeteerSitemap.md
@@ -10,12 +10,15 @@ In local configuration, the results are stored as JSON files in `./apify_storage
To run this example on the Apify Platform, select the `Node.js 8 + Chrome on Debian (apify/actor-node-chrome)` base image
on the source tab of your actor configuration.
+
```javascript
-const Apify = require('apify');
+const Apify = require("apify");
Apify.main(async () => {
const requestList = new Apify.RequestList({
- sources: [{ requestsFromUrl: 'https://edition.cnn.com/sitemaps/cnn/news.xml' }],
+ sources: [
+ { requestsFromUrl: "https://edition.cnn.com/sitemaps/cnn/news.xml" }
+ ]
});
await requestList.initialize();
@@ -26,12 +29,12 @@ Apify.main(async () => {
await Apify.pushData({
url: request.url,
title: await page.title(),
- html: await page.content(),
+ html: await page.content()
});
- },
+ }
});
await crawler.run();
- console.log('Done.');
+ console.log("Done.");
});
-```
\ No newline at end of file
+```
diff --git a/docs/examples/PuppeteerWithProxy.md b/docs/examples/PuppeteerWithProxy.md
index ae38887b5..f37cc945b 100644
--- a/docs/examples/PuppeteerWithProxy.md
+++ b/docs/examples/PuppeteerWithProxy.md
@@ -13,23 +13,24 @@ or run the script using the CLI.
To run this example on the Apify Platform, select the `Node.js 8 + Chrome on Debian (apify/actor-node-chrome)` base image
on the source tab of your actor configuration.
+
```javascript
-const Apify = require('apify');
+const Apify = require("apify");
Apify.main(async () => {
// Apify.launchPuppeteer() is similar to Puppeteer's launch() function.
// It accepts the same parameters and returns a preconfigured Puppeteer.Browser instance.
// Moreover, it accepts several additional options, such as useApifyProxy.
const options = {
- useApifyProxy: true,
+ useApifyProxy: true
};
const browser = await Apify.launchPuppeteer(options);
- console.log('Running Puppeteer script...');
+ console.log("Running Puppeteer script...");
// Proceed with a plain Puppeteer script.
const page = await browser.newPage();
- const url = 'https://en.wikipedia.org/wiki/Main_Page';
+ const url = "https://en.wikipedia.org/wiki/Main_Page";
await page.goto(url);
const title = await page.title();
@@ -37,6 +38,6 @@ Apify.main(async () => {
// Cleaning up after yourself is always good.
await browser.close();
- console.log('Puppeteer closed.');
+ console.log("Puppeteer closed.");
});
-```
\ No newline at end of file
+```
diff --git a/docs/examples/Screenshots.md b/docs/examples/Screenshots.md
index 3087abd24..65a390932 100644
--- a/docs/examples/Screenshots.md
+++ b/docs/examples/Screenshots.md
@@ -16,7 +16,12 @@ In local configuration, the input is stored in the default key-value store's dir
`./apify_storage/key_value_stores/default/INPUT.json`. You need to create the file and set it with the following content:
```json
-{ "sources": [{ "url": "https://www.google.com" }, { "url": "https://www.duckduckgo.com" }] }
+{
+ "sources": [
+ { "url": "https://www.google.com" },
+ { "url": "https://www.duckduckgo.com" }
+ ]
+}
```
On the Apify cloud, the input can be either set manually
@@ -27,14 +32,15 @@ in the Apify Actor documentation.
To run this example on the Apify Platform, select the `Node.js 8 + Chrome on Debian (apify/actor-node-chrome)` base image
on the source tab of your actor configuration.
+
```javascript
-const Apify = require('apify');
+const Apify = require("apify");
Apify.main(async () => {
// Read the actor input configuration containing the URLs for the screenshot.
// By convention, the input is present in the actor's default key-value store under the "INPUT" key.
const input = await Apify.getInput();
- if (!input) throw new Error('Have you passed the correct INPUT ?');
+ if (!input) throw new Error("Have you passed the correct INPUT ?");
const { sources } = input;
@@ -50,19 +56,21 @@ Apify.main(async () => {
const screenshotBuffer = await page.screenshot();
// The record key may only include the following characters: a-zA-Z0-9!-_.'()
- const key = request.url.replace(/[:/]/g, '_');
+ const key = request.url.replace(/[:/]/g, "_");
// Save the screenshot. Choosing the right content type will automatically
// assign the local file the right extension, in this case .png.
// The screenshots will be stored in ./apify_storage/key_value_stores/default/
- await Apify.setValue(key, screenshotBuffer, { contentType: 'image/png' });
+ await Apify.setValue(key, screenshotBuffer, {
+ contentType: "image/png"
+ });
console.log(`Screenshot of ${request.url} saved.`);
- },
+ }
});
// Run crawler.
await crawler.run();
- console.log('Crawler finished.');
+ console.log("Crawler finished.");
});
-```
\ No newline at end of file
+```
diff --git a/docs/examples/SynchronousRun.md b/docs/examples/SynchronousRun.md
index e26813292..a45a7ebe8 100644
--- a/docs/examples/SynchronousRun.md
+++ b/docs/examples/SynchronousRun.md
@@ -13,39 +13,41 @@ can be invoked synchronously using a single HTTP request to directly obtain its
Apify API endpoint. The example is also shared as the
<a href="https://apify.com/apify/example-golden-gate-webcam" target="_blank">apify/example-golden-gate-webcam</a>
actor in the Apify library, so you can test it directly there simply by sending a POST request to
+
```http
https://api.apify.com/v2/acts/apify~example-golden-gate-webcam/run-sync?token=[YOUR_API_TOKEN]
```
To run this example on the Apify Platform, select the `Node.js 8 + Chrome on Debian (apify/actor-node-chrome)` base image
on the source tab of your actor configuration.
+
```javascript
-const Apify = require('apify');
+const Apify = require("apify");
Apify.main(async () => {
// Launch web browser.
const browser = await Apify.launchPuppeteer();
// Load http://goldengatebridge75.org/news/webcam.html and get an IFRAME with the webcam stream
- console.log('Opening web page...');
+ console.log("Opening web page...");
const page = await browser.newPage();
- await page.goto('http://goldengatebridge75.org/news/webcam.html');
+ await page.goto("http://goldengatebridge75.org/news/webcam.html");
const iframe = (await page.frames()).pop();
// Get webcam image element handle.
- const imageElementHandle = await iframe.$('.VideoColm img');
+ const imageElementHandle = await iframe.$(".VideoColm img");
// Give the webcam image some time to load.
- console.log('Waiting for page to load...');
+ console.log("Waiting for page to load...");
await Apify.utils.sleep(3000);
// Get a screenshot of that image.
const imageBuffer = await imageElementHandle.screenshot();
- console.log('Screenshot captured.');
+ console.log("Screenshot captured.");
// Save the screenshot as the actor's output. By convention, similarly to "INPUT",
// the actor's output is stored in the default key-value store under the "OUTPUT" key.
- await Apify.setValue('OUTPUT', imageBuffer, { contentType: 'image/jpeg' });
- console.log('Actor finished.');
+ await Apify.setValue("OUTPUT", imageBuffer, { contentType: "image/jpeg" });
+ console.log("Actor finished.");
});
-```
\ No newline at end of file
+```
diff --git a/docs/guides/data_storage.md b/docs/guides/data_storage.md
index 3913c5bd7..57af6a997 100644
--- a/docs/guides/data_storage.md
+++ b/docs/guides/data_storage.md
@@ -16,9 +16,9 @@ No code changes are needed.
**Related links**
-* <a href="https://apify.com/docs/storage" target="_blank">Apify cloud storage documentation</a>
-* <a href="https://my.apify.com/storage" target="_blank">View storage in Apify app</a>
-* <a href="https://apify.com/docs/api/v2#/reference/key-value-stores" target="_blank">API reference</a>
+- <a href="https://apify.com/docs/storage" target="_blank">Apify cloud storage documentation</a>
+- <a href="https://my.apify.com/storage" target="_blank">View storage in Apify app</a>
+- <a href="https://apify.com/docs/api/v2#/reference/key-value-stores" target="_blank">API reference</a>
## Key-value store
@@ -57,27 +57,26 @@ The following code demonstrates basic operations of key-value stores:
const input = await Apify.getInput();
// Write actor output to the default key-value store.
-await Apify.setValue('OUTPUT', { myResult: 123 });
+await Apify.setValue("OUTPUT", { myResult: 123 });
// Open a named key-value store
-const store = await Apify.openKeyValueStore('some-name');
+const store = await Apify.openKeyValueStore("some-name");
// Write record. JavaScript object is automatically converted to JSON,
// strings and binary buffers are stored as they are
-await store.setValue('some-key', { foo: 'bar' });
+await store.setValue("some-key", { foo: "bar" });
// Read record. Note that JSON is automatically parsed to a JavaScript object,
// text data returned as a string and other data is returned as binary buffer
-const value = await store.getValue('some-key');
+const value = await store.getValue("some-key");
// Delete record
-await store.setValue('some-key', null);
+await store.setValue("some-key", null);
```
To see a real-world example of how to get the input from the key-value store, see the
[Screenshots](../examples/screenshots) example.
-
## Dataset
Datasets are used to store structured data
@@ -116,25 +115,21 @@ The following code demonstrates basic operations of the dataset:
```javascript
// Write a single row to the default dataset
-await Apify.pushData({ col1: 123, col2: 'val2' });
+await Apify.pushData({ col1: 123, col2: "val2" });
// Open a named dataset
-const dataset = await Apify.openDataset('some-name');
+const dataset = await Apify.openDataset("some-name");
// Write a single row
-await dataset.pushData({ foo: 'bar' });
+await dataset.pushData({ foo: "bar" });
// Write multiple rows
-await dataset.pushData([
- { foo: 'bar2', col2: 'val2' },
- { col3: 123 },
-]);
+await dataset.pushData([{ foo: "bar2", col2: "val2" }, { col3: 123 }]);
```
To see how to use the dataset to store crawler results, see the
[Cheerio Crawler](../examples/cheeriocrawler) example.
-
## Request queue
The request queue is a storage of URLs to crawl.
@@ -167,12 +162,15 @@ The following code demonstrates basic operations of the request queue:
const queue = await Apify.openRequestQueue();
// Open a named request queue
-const queueWithName = await Apify.openRequestQueue('some-name');
+const queueWithName = await Apify.openRequestQueue("some-name");
// Enqueue few requests
-await queue.addRequest({ url: 'http://example.com/aaa'});
-await queue.addRequest({ url: 'http://example.com/bbb'});
-await queue.addRequest({ url: 'http://example.com/foo/bar'}, { forefront: true });
+await queue.addRequest({ url: "http://example.com/aaa" });
+await queue.addRequest({ url: "http://example.com/bbb" });
+await queue.addRequest(
+ { url: "http://example.com/foo/bar" },
+ { forefront: true }
+);
// Get requests from queue
const request1 = await queue.fetchNextRequest();
diff --git a/docs/guides/getting_started.md b/docs/guides/getting_started.md
index 252634078..9f61defc2 100644
--- a/docs/guides/getting_started.md
+++ b/docs/guides/getting_started.md
@@ -2,24 +2,27 @@
id: gettingstarted
title: Getting Started
---
+
Without the right tools, crawling and scraping the web can be a difficult thing. At the very least, you need an HTTP client to make the necessary requests, but that only gets you raw HTML and sometimes not even that. Then you have to read this HTML and extract the data you're interested in. Once extracted, it must be stored in a machine readable format and easily accessible for further processing, because it is the processed data that hold value.
Apify SDK covers the process end-to-end. From crawling the web for links and scraping the raw data to storing it in various machine readable formats, ready for processing. With this guide in hand, you should have your own data extraction solutions up and running in a few hours.
## Intro
+
The goal of this getting started guide is to provide a step-by-step introduction to all the features of the Apify SDK. It will walk you through creating the simplest of crawlers that only print text to console, all the way up to complex systems that crawl pages, interact with them as if a real user were sitting in front of a real browser and output structured data.
-Since Apify SDK is usable both locally on any computer and on the
+Since Apify SDK is usable both locally on any computer and on the
<a href="https://my.apify.com" target="_blank">Apify Platform</a>,
you will be able to use the source code in both environments interchangeably. Nevertheless, some initial setup is still required, so choose your preferred starting environment and let's get into it.
## Setting up locally
+
To run Apify SDK on your own computer, you need to meet the following pre-requisites first:
1. Have Node.js version 8.14 or higher installed.
- * Visit <a href="https://nodejs.org/en/download/" target="_blank">Node.js website</a> to download or use <a href="https://github.com/creationix/nvm" target="_blank">nvm</a>
+ - Visit <a href="https://nodejs.org/en/download/" target="_blank">Node.js website</a> to download or use <a href="https://github.com/creationix/nvm" target="_blank">nvm</a>
2. Have NPM installed.
- * NPM comes bundled with Node.js so you should already have it. If not, reinstall Node.js.
+ - NPM comes bundled with Node.js so you should already have it. If not, reinstall Node.js.
If you're not certain, confirm the pre-requisites by running:
@@ -32,7 +35,8 @@ npm -v
```
### Creating a new project
-The fastest and best way to create new projects with the Apify SDK is to use our own
+
+The fastest and best way to create new projects with the Apify SDK is to use our own
<a href="https://www.npmjs.com/package/apify-cli" target="_blank">Apify CLI</a>.
This command line tool allows you to create, run and manage Apify projects with ease, including their deployment to the <a href="https://my.apify.com" target="_blank">Apify Platform</a> if you wish to run them in the cloud after developing them locally.
@@ -41,11 +45,13 @@ Let's install the Apify CLI with the following command:
```bash
npm install -g apify-cli
```
+
Once the installation finishes, all you need to do to set up an Apify SDK project is to run:
```bash
apify create my-new-project
```
+
A prompt will be shown, asking to choose a template. Disregard the different options for now and choose the template labeled `Hello world`. The command will now create a new directory in your current working directory, called `my-new-project`, create a `package.json` in this folder and install all the necessary dependencies. It will also add example source code that you can immediately run.
Let's try that!
@@ -53,6 +59,7 @@ Let's try that!
```bash
cd my-new-project
```
+
```bash
apify run -p
```
@@ -66,9 +73,11 @@ You can always terminate the crawl with a keypress in the terminal:
```bash
CTRL+C
```
+
Did you see all that? If you did, congratulations! You're ready to go!
## Setting up on the Apify Platform
+
Maybe you don't have Node.js installed and don't want the hassle. Or you can't install anything on your computer because you're using a company provided one. Or perhaps you'd just prefer to start working in the cloud right away. Well, no worries, we've got you covered.
The <a href="https://my.apify.com" target="_blank">Apify Platform</a> is the foundational product of <a href="https://apify.com" target="_blank">Apify</a>. It's a serverless cloud computing platform, specifically designed for any web automation jobs, that may include crawling and scraping, but really works amazing for any batch jobs and long running tasks.
@@ -80,6 +89,7 @@ and create one, if you haven't already. Don't forget to verify your email. Witho
Once you're in, you might be prompted by our in-app help to walk through a step-by-step guide into some of our new features. Feel free to finish that, if you'd like, but once you're done, click on the **Actors** tab in the left menu. To read more about **Actors**, see: [What is an Actor](./whatisanactor).
### Creating a new project
+
In the page that shows after clicking on Actors in the left menu, choose **Create new**. Give it a name in the form that opens, let's say, `my-new-actor`. Disregard all the available options for now and save your changes.
Now click on the **Sources** tab at the top. Disregard the version and environment variables inputs for now and proceed directly to **Source code**. This is where you develop the actor, if you choose not to do it locally. Just press **Run** below the **Source code** panel. It will automatically build and run the example source code. You should start seeing log messages that represent the build and after the build is complete, log messages of the running actor. Feel free to check out the other **Run** tabs, such as **Info**, where you can find useful information about the run, or **Key-value-store**, where the actor's **INPUT** and **OUTPUT** are stored.
@@ -89,23 +99,27 @@ Good job. You're now ready to run your own source code on the Apify Platform. Fo
where you'll find everything about the platform's various options.
## First crawler
+
Whether you've chosen to develop locally or in the cloud, it's time to start writing some actual source code. But before we do, let me just briefly introduce all the Apify SDK classes necessary to make it happen.
### The general idea
+
There are 3 crawler classes available for use in the Apify SDK. [`BasicCrawler`](../api/basiccrawler), [`CheerioCrawler`](../api/cheeriocrawler) and [`PuppeteerCrawler`](../api/puppeteercrawler). We'll talk about their differences later. Now, let's talk about what they have in common.
All the crawlers' general idea is to go to a web page, open it, do some stuff there, save some results and continue to the next page, until it's done its job. So each time the crawler needs to find answers to two questions: **Where should I go?** and **What should I do there?**. Answering those two questions is the only setup mandatory to run the crawlers.
### The Where - `Request`, `RequestList` and `RequestQueue`
+
All crawlers use instances of the [`Request`](../api/request) class to determine where they need to go. Each request may hold a lot of information, but at the very least, it must hold a URL - a web page to open. But having only one URL would not make sense for crawling. We need to either have a pre-existing list of our own URLs that we wish to visit, perhaps a thousand, or a million, or we need to build this list dynamically as we crawl, adding more and more URLs to the list as we progress.
A representation of the pre-existing list is an instance of the [`RequestList`](../api/requestlist) class. It is a static, immutable list of URLs and other metadata (see the [`Request`](../api/request) object) that the crawler will visit, one by one, retrying whenever an error occurs, until there are no more `Requests` to process.
-[`RequestQueue`](../api/requestqueue) on the other hand, represents a dynamic queue of `Requests`. One that can be updated at runtime by adding more pages - `Requests` to process. This allows the crawler to open one page, extract interesting URLs, such as links to other pages on the same domain, add them to the queue (called *enqueuing*) and repeat this process to build a queue of tens of thousands or more URLs while knowing only a single one at the beginning.
+[`RequestQueue`](../api/requestqueue) on the other hand, represents a dynamic queue of `Requests`. One that can be updated at runtime by adding more pages - `Requests` to process. This allows the crawler to open one page, extract interesting URLs, such as links to other pages on the same domain, add them to the queue (called _enqueuing_) and repeat this process to build a queue of tens of thousands or more URLs while knowing only a single one at the beginning.
`RequestList` and `RequestQueue` are essential for the crawler's operation. There is no other way to supply `Requests` = "pages to crawl" to the crawlers. At least one of them always needs to be provided while setting up. You can also use both at the same time, if you wish.
### The What - `handlePageFunction`
+
The `handlePageFunction` is the brain of the crawler. It tells it what to do at each and every page it visits. Generally it handles extraction of data from the page, processing the data, saving it, calling APIs, doing calculations and whatever else you need it to do, really.
The `handlePageFunction` is provided by you, the user, and invoked automatically by the crawler for each `Request` from either the `RequestList` or `RequestQueue`. It always receives a single argument and that is a plain `Object`. Its properties change depending on the used crawler class, but it always includes at least the `request` property, which represents the currently crawled `Request` instance (i.e. the URL the crawler is visiting and related metadata) and the `autoscaledPool` property, which is an instance of the [`AutoscaledPool`](../api/autoscaledpool) class and we'll talk about it in detail later.
@@ -119,27 +133,29 @@ The `handlePageFunction` is provided by you, the user, and invoked automatically
```
### Putting it all together
+
Enough theory! Let's put some of those hard learned facts into practice. We learned above that we need `Requests` and a `handlePageFunction` to setup a crawler. We will also use the [`Apify.main()`](../api/apify#module_Apify.main) function. It's not mandatory, but it makes our life easier. We'll learn about it in detail later on.
Let's start super easy. Visit one page, get its title and close. First of all we need to require Apify, to make all of its features available to us:
```js
-const Apify = require('apify');
+const Apify = require("apify");
```
Easy right? It doesn't get much more difficult, trust me. For the purposes of this tutorial, we'll be scraping our own webpage <a href="https://apify.com" target="_blank">https://apify.com</a>. Now, to get there, we need a `Request` with the page's URL in one of our sources, `RequestList` or `RequestQueue`. Let's go with `RequestQueue` for now.
```js
-const Apify = require('apify');
+const Apify = require("apify");
// This is how you use the Apify.main() function.
Apify.main(async () => {
// First we create the request queue instance.
const requestQueue = await Apify.openRequestQueue();
// And then we add a request to it.
- await requestQueue.addRequest({ url: 'https://apify.com' });
+ await requestQueue.addRequest({ url: "https://apify.com" });
});
```
+
> If you're not familiar with the `async` and `await` keywords used in the example, trust that it is a native syntax in modern JavaScript and you can [learn more about it here](https://nikgrozev.com/2017/10/01/async-await/).
The [`requestQueue.addRequest()`](../api/requestqueue#RequestQueue+addRequest) function automatically converts the plain object we passed to it to a `Request` instance, so now we have a `requestQueue` that holds one `request` which points to `https://apify.com`. Now we need the `handlePageFunction`.
@@ -149,33 +165,33 @@ The [`requestQueue.addRequest()`](../api/requestqueue#RequestQueue+addRequest) f
const handlePageFunction = async ({ request, $ }) => {
// This should look familiar if you ever worked with jQuery.
// We're just getting the text content of the <title> HTML element.
- const title = $('title').text();
-
+ const title = $("title").text();
+
console.log(`The title of "${request.url}" is: ${title}.`);
-}
+};
```
Wait, where did the `$` come from? Remember what we learned about the `handlePageFunction` earlier. It expects a plain `Object` as an argument that will always have a `request` property, but it will also have other properties, depending on the chosen crawler class. Well, `$` is a property provided by the `CheerioCrawler` class which we'll set up right now.
```js
-const Apify = require('apify');
+const Apify = require("apify");
Apify.main(async () => {
const requestQueue = await Apify.openRequestQueue();
- await requestQueue.addRequest({ url: 'https://apify.com' });
-
+ await requestQueue.addRequest({ url: "https://apify.com" });
+
const handlePageFunction = async ({ request, $ }) => {
- const title = $('title').text();
-
+ const title = $("title").text();
+
console.log(`The title of "${request.url}" is: ${title}.`);
- }
-
+ };
+
// Set up the crawler, passing a single options object as an argument.
const crawler = new Apify.CheerioCrawler({
requestQueue,
handlePageFunction
});
-
+
await crawler.run();
});
```
@@ -188,12 +204,13 @@ To run the code on Apify Platform, just replace the original example with your n
Whichever environment you choose, you should see the message `The title of "https://apify.com" is: Web Scraping, Data Extraction and Automation - Apify.` printed to the screen. If you do, congratulations and let's move onto some bigger challenges! And if you feel like you don't really know what just happened there, no worries, it will all become clear when you learn more about the `CheerioCrawler`.
-
## CheerioCrawler aka jQuery crawler
+
This is the crawler that we used in our earlier example. Our simplest and also the fastest crawling solution. If you're familiar with `jQuery`, you'll understand [`CheerioCrawler`](../api/cheeriocrawler) in minutes. <a href="https://www.npmjs.com/package/cheerio" target="_blank">Cheerio</a> is essentially `jQuery` for Node.js. It offers the same API, including the familiar `$` object. You can use it, as you would `jQuery`, for manipulating the DOM of a HTML page. In crawling, you'll mostly use it to select the right elements and extract their text values - the data you're interested in. But `jQuery` runs in a browser and attaches directly to the browser's DOM. Where does `cheerio` get its HTML? This is where the `Crawler` part of [`CheerioCrawler`](../api/cheeriocrawler) comes in.
### Overview
-[`CheerioCrawler`](../api/cheeriocrawler) crawls by making plain HTTP requests to the provided URLs. As you remember from the previous section, the URLs are fed to the crawler using either the [`RequestList`](../api/cheeriocrawler) or the [`RequestQueue`](../api/cheeriocrawler). The HTTP responses it gets back are HTML pages, the same pages you would get in your browser when you first load a URL.
+
+[`CheerioCrawler`](../api/cheeriocrawler) crawls by making plain HTTP requests to the provided URLs. As you remember from the previous section, the URLs are fed to the crawler using either the [`RequestList`](../api/cheeriocrawler) or the [`RequestQueue`](../api/cheeriocrawler). The HTTP responses it gets back are HTML pages, the same pages you would get in your browser when you first load a URL.
> Note, however, that modern web pages often do not serve all of their content in the first HTML response, but rather the first HTML contains links to other resources such as CSS and JavaScript that get downloaded afterwards and together they create the final page. See our [`PuppeteerCrawler`](../api/puppeteercrawler) to crawl those.
@@ -203,126 +220,146 @@ Example use of Cheerio and its `$` function in comparison to browser JavaScript:
```js
// Return the text content of the <title> element.
-document.querySelector('title').textContent; // plain JS
-$('title').text(); // Cheerio
+document.querySelector("title").textContent; // plain JS
+$("title").text(); // Cheerio
// Return an array of all 'href' links on the page.
-Array.from(document.querySelectorAll('[href]')).map(el => el.href) // plain JS
-$('[href]').map((i, el) => $(el).attr('href')).get(); // Cheerio
+Array.from(document.querySelectorAll("[href]")).map(el => el.href); // plain JS
+$("[href]")
+ .map((i, el) => $(el).attr("href"))
+ .get(); // Cheerio
```
+
> This is not to show that Cheerio is better than plain browser JavaScript. Some might actually prefer the more expressive way plain JS provides. Unfortunately, the browser JavaScript methods are not available in Node.js, so Cheerio is our best bet to do the parsing.
### When to use [`CheerioCrawler`](../api/cheeriocrawler)
+
Even though using `CheerioCrawler` is extremely easy, it probably will not be your first choice for most kinds of crawling or scraping in production environments. Since most websites nowadays use modern JavaScript to create rich, responsive and data driven user experiences, the plain HTTP requests the crawler uses may just fall short of your needs.
-But `CheerioCrawler` is far from useless! It really shines when you need to do extremely high workloads. With just 4 GBs of memory and a single CPU core, you can scrape 500 or more pages a minute! *(assuming each page contains approximately 400KB of HTML)* To get this high with a full browser scraper, such as the [`PuppeteerCrawler`](../api/puppeteercrawler), you'd need significantly more computing power.
+But `CheerioCrawler` is far from useless! It really shines when you need to do extremely high workloads. With just 4 GBs of memory and a single CPU core, you can scrape 500 or more pages a minute! _(assuming each page contains approximately 400KB of HTML)_ To get this high with a full browser scraper, such as the [`PuppeteerCrawler`](../api/puppeteercrawler), you'd need significantly more computing power.
**Advantages:**
- - Extremely fast
- - Easy to set up
- - Familiar for jQuery users
- - Super cheap to run
- - Each request can go through a different proxy
+- Extremely fast
+- Easy to set up
+- Familiar for jQuery users
+- Super cheap to run
+- Each request can go through a different proxy
**Disadvantages:**
- - Does not work for all websites
- - May easily overload the target website with requests
- - Does not enable any manipulation of the website before scraping
+- Does not work for all websites
+- May easily overload the target website with requests
+- Does not enable any manipulation of the website before scraping
### Basic use of [`CheerioCrawler`](../api/cheeriocrawler)
+
Now that we have an idea of the crawler's inner workings, let's build one. We'll use the example from the previous section and improve on it by letting it truly crawl the page, finding new links as it goes, enqueuing them into the `RequestQueue` and then scraping them.
#### Refresher
+
Just to refresh your memory, in the previous section we built a very simple crawler that downloads HTML of a single page, reads its title and prints it to the console. This is the original source code:
```js
-const Apify = require('apify');
+const Apify = require("apify");
Apify.main(async () => {
const requestQueue = await Apify.openRequestQueue();
- await requestQueue.addRequest({ url: 'https://apify.com' });
-
+ await requestQueue.addRequest({ url: "https://apify.com" });
+
const handlePageFunction = async ({ request, $ }) => {
- const title = $('title').text();
-
+ const title = $("title").text();
+
console.log(`The title of "${request.url}" is: ${title}.`);
- }
-
+ };
+
// Set up the crawler, passing a single options object as an argument.
const crawler = new Apify.CheerioCrawler({
requestQueue,
handlePageFunction
});
-
+
await crawler.run();
});
```
+
Earlier we said that we would let the crawler:
- 1. Find new links on the page
- 2. Filter only those pointing to `apify.com`
- 3. Enqueue them to the `RequestQueue`
- 4. Scrape the newly enqueued links
+1. Find new links on the page
+2. Filter only those pointing to `apify.com`
+3. Enqueue them to the `RequestQueue`
+4. Scrape the newly enqueued links
So let's get to it!
#### Finding new links
+
There are numerous approaches to finding links to follow when crawling the web. For our purposes, we will be looking for `<a>` elements that contain the `href` attribute. For example `<a href="https://apify.com/store>This is a link to Apify Store</a>`. To do this, we need to update our Cheerio function.
```js
-const links = $('a[href]').map((i, el) => $(el).attr('href')).get();
+const links = $("a[href]")
+ .map((i, el) => $(el).attr("href"))
+ .get();
```
Our new function finds all the `<a>` elements that contain the `href` attribute and extracts the attributes into an array of strings. There is a problem though. There can be relative links in the list and those can't be used on their own. We need to resolve them using our domain as base URL and we will use one of Node.js' standard libraries to do this.
```js
// At the top of the file:
-const { URL } = require('url');
+const { URL } = require("url");
// ...
-const ourDomain = 'https://apify.com';
+const ourDomain = "https://apify.com";
const absoluteUrls = links.map(link => new URL(link, ourDomain));
```
#### Filtering links to same domain
+
Websites typically contain a lot of links that lead away from the original page. This is normal, but when crawling a website, we usually want to crawl this one site and do not let our crawler wander away to Google, Facebook and Twitter. Therefore, we need to filter out the off-domain links and only keep the ones that lead to the same domain.
> Don't worry, we'll learn how to do this with a single function call using Apify in a few moments.
```js
// At the top of the file:
-const { URL } = require('url');
+const { URL } = require("url");
// ...
-const links = $('a[href]').map((i, el) => $(el).attr('href')).get();
+const links = $("a[href]")
+ .map((i, el) => $(el).attr("href"))
+ .get();
-const ourDomain = 'apify.com'
+const ourDomain = "apify.com";
const absoluteUrls = links.map(link => new URL(link, ourDomain));
-const sameDomainLinks = absoluteUrls.filter(url => url.href.startsWith(ourDomain));
+const sameDomainLinks = absoluteUrls.filter(url =>
+ url.href.startsWith(ourDomain)
+);
// ...
```
#### Enqueueing links to `RequestQueue`
+
This should be easy, because we already did that [earlier](#puttingitalltogether), remember? Just call `requestQueue.addRequest()` for all the new links. This will add them to the end of the queue for processing.
```js
// At the top of the file:
-const { URL } = require('url');
+const { URL } = require("url");
// ...
-const links = $('a[href]').map((i, el) => $(el).attr('href')).get();
+const links = $("a[href]")
+ .map((i, el) => $(el).attr("href"))
+ .get();
-const ourDomain = 'https://apify.com';
+const ourDomain = "https://apify.com";
const absoluteUrls = links.map(link => new URL(link, ourDomain));
-const sameDomainLinks = absoluteUrls.filter(url => url.href.startsWith(ourDomain));
+const sameDomainLinks = absoluteUrls.filter(url =>
+ url.href.startsWith(ourDomain)
+);
// Add the requests in series. There's of course room for speed
// improvement by parallelization. Try to implement it, if you wish.
@@ -335,9 +372,11 @@ for (const url of sameDomainLinks) {
```
#### Scrape the newly enqueued links
+
And we're approching the finishing line. All we need to do now is just integrate the new code into our original crawler. It will be easy, because almost everything needs to go into the `handlePageFunction`. But just before we do that, let me introduce the first crawler configuration option, that is not a `handlePageFunction` or `requestQueue`. It's called `maxRequestsPerCrawl`.
##### The `maxRequestsPerCrawl` limit
+
This configuration option is available in all crawler classes and you can use it to limit the number of `Requests` the crawler should process. It's very useful when you're just testing your code or when your crawler could potentially crawl millions of pages and you want to save resources. You can add it to the crawler options like this:
```js
@@ -346,59 +385,68 @@ const crawler = new Apify.CheerioCrawler({
requestQueue,
handlePageFunction
});
-
```
+
This limits the number of successfully handled `Requests` to 20. Bear in mind that the actual number of processed requests might be a little higher and that's because usually there are multiple `Requests` processed at the same time and once the 20th `Request` finishes, the other running `Requests` will be allowed to finish too.
#### Putting it all together
+
```js
-const { URL } = require('url'); // <------ This is new.
-const Apify = require('apify');
+const { URL } = require("url"); // <------ This is new.
+const Apify = require("apify");
Apify.main(async () => {
const requestQueue = await Apify.openRequestQueue();
- await requestQueue.addRequest({ url: 'https://apify.com' });
-
+ await requestQueue.addRequest({ url: "https://apify.com" });
+
const handlePageFunction = async ({ request, $ }) => {
- const title = $('title').text();
+ const title = $("title").text();
console.log(`The title of "${request.url}" is: ${title}.`);
-
+
// Here starts the new part of handlePageFunction.
- const links = $('a[href]').map((i, el) => $(el).attr('href')).get();
+ const links = $("a[href]")
+ .map((i, el) => $(el).attr("href"))
+ .get();
- const ourDomain = 'https://apify.com';
+ const ourDomain = "https://apify.com";
const absoluteUrls = links.map(link => new URL(link, ourDomain));
- const sameDomainLinks = absoluteUrls.filter(url => url.href.startsWith(ourDomain));
-
+ const sameDomainLinks = absoluteUrls.filter(url =>
+ url.href.startsWith(ourDomain)
+ );
+
console.log(`Enqueueing ${sameDomainLinks.length} URLs.`);
for (const url of sameDomainLinks) {
await requestQueue.addRequest({ url: url.href });
}
};
-
+
const crawler = new Apify.CheerioCrawler({
maxRequestsPerCrawl: 20, // <------ This is new too.
requestQueue,
handlePageFunction
});
-
+
await crawler.run();
});
```
+
No matter if you followed along with our coding or just copy pasted the resulting source, try running it now, perhaps even in both environments. You should see the crawler log the **title** of the first page, then the **enqueueing** message showing number of URLs, followed by the **title** of the first enqueued page and so on and so on.
> If you need help with running the code, refer back to the chapters on environment setup: [Setting up locally](#settinguplocally) and [Setting up on the Apify Platform](#settingupontheapifyplatform).
## Using Apify SDK to enqueue links like a boss
+
If you were paying attention carefully in the previous chapter, we said that we would show a way to enqueue new `Requests` with a single function call. You might be wondering why we had to go through the whole process of getting the individual links, filtering the same domain ones and then manually enqueuing them into the `RequestQueue`, when there is a simpler way.
Well, the obvious reason is practice. This is a tutorial after all. The other reason is to make you think about all the bits and pieces that come together, so that in the end, a new page, not previously entered in by you, can be scraped. We think that by seeing the bigger picture, you will be able to get the most out of Apify SDK.
### Meet `Apify.utils`
+
We will talk at length about them later, but in short, `Apify.utils` is a namespace where you can find various helpful functions and constants that make your life easier. One of the available functions is `Apify.utils.enqueueLinks()` which encapsulates the whole enqueueing process and even adds some extra functionality.
### Introduction to `Apify.utils.enqueueLinks()`
+
Since enqueuing new links to crawl is such an integral part of web crawling, we created a function that attempts to simplify this process as much as possible. With a single function call, it allows you to find all the links on a page that match specified criteria and add them to a `RequestQueue`. It also allows you to modify the resulting `Requests` to match your crawling needs.
`enqueueLinks` is quite a powerful function so, like crawlers, it gets its arguments from an options object. This is useful, because you don't have to remember their order! But also because we can easily extend its API and add new features. You can [find the full reference here](../api/utils#utils.enqueuelinks).
@@ -406,22 +454,27 @@ Since enqueuing new links to crawl is such an integral part of web crawling, we
We suggest using ES6 destructuring to grab the `enqueueLinks()` function off of the `utils` object, so you don't have to type `Apify.utils` all the time.
```js
-const Apify = require('apify');
-const { utils: { enqueueLinks } } = Apify;
+const Apify = require("apify");
+const {
+ utils: { enqueueLinks }
+} = Apify;
// Now you can use enqueueLinks like this:
-await enqueueLinks({ /* options */ });
-
+await enqueueLinks({
+ /* options */
+});
```
+
### Basic use of `enqueueLinks()` with `CheerioCrawler`
+
We already implemented logic that takes care of enqueueing new links to a `RequestQueue` in the previous chapter on `CheerioCrawler`. Let's look at that logic and implement the same functionality using `enqueueLinks()`.
We found that the crawler needed to do these 4 things to crawl `apify.com`:
- 1. Find new links on the page
- 2. Filter only those pointing to `apify.com`
- 3. Enqueue them to the `RequestQueue`
- 4. Scrape the newly enqueued links
+1. Find new links on the page
+2. Filter only those pointing to `apify.com`
+3. Enqueue them to the `RequestQueue`
+4. Scrape the newly enqueued links
Using `enqueueLinks()` we can squash the first 3 into a single function call, if we set the options correctly. For now, let's just stick to the basics. At the very least, we need a source where to find the links and the queue to enqueue them to. The `$` Cheerio object is one of the sources the function accepts and we already know how to work with it in the `handlePageFunction`. We also know how to get a `requestQueue` instance.
@@ -429,9 +482,11 @@ Using `enqueueLinks()` we can squash the first 3 into a single function call, if
// Assuming previous existence of the '$' and 'requestQueue' variables.
await enqueueLinks({ $, requestQueue });
```
+
That's all we need to do to enqueue all `<a href="...">` links from the given page to the given queue. Easy, right? Scratch number 1 and 3 off the list. Only number 2 remains and to tackle this one, we need to talk about yet another new concept, the pseudo-URL.
#### Introduction to pseudo-URLs
+
Pseudo-URLs are represented by our `PseudoUrl` class and even though the name sounds discouraging, they're a pretty simple concept. They're just URLs with some parts replaced by wildcards (read <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">regular expressions</a>). They are matched against URLs to find specific links, domains, patterns, file extensions and so on.
In scraping, there usually are patterns to be found in the websites' URLs that can be leveraged to scrape only the pages we're interested in. Imagine a typical online store. It has different categories which list different items The URL for might looks something like this:
@@ -445,6 +500,7 @@ A category would then have a different URL:
```
https://www.online-store.com/categories/computers
```
+
Going to this page would produce a list of offered computers. Then, clicking on one of the computers might take us to a detail URL:
```
@@ -454,13 +510,15 @@ https://www.online-store.com/items/613804
As you can see, there's a structure to the links. In the real world, the structure might not always be perfectly obvious, but it's very often there. Pseudo-URLs help to use this structure to select only the relevant links from a given page.
#### Structure of a pseudo-URL
+
Pseudo-URL is a URL with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">regular expressions</a>) enclosed in `[]` brackets. Since we're running Node.js, the regular expressions should follow the JavaScript style.
-For example, a pseudo-URL
+For example, a pseudo-URL
```
https://www.online-store.com/categories/[(\w|-)+]
```
+
will match all of the following URLs:
```
@@ -468,6 +526,7 @@ https://www.online-store.com/categories/computers
https://www.online-store.com/categories/mobile-phones
https://www.online-store.com/categories/black-friday
```
+
but it will not match
```
@@ -502,6 +561,7 @@ www.online-store.org/items/7003
> Pssst! Don't tell anyone, but you can create `PseudoUrls` with plain old `RegExp` instances instead of this brackety madness as well.
#### Using `enqueueLinks()` to filter links
+
That's been quite a lot of theory and examples. We might as well put it to practice. Going back to our `CheerioCrawler` exercise, we still have number 2 left to cross off the list - filter links pointing to `apify.com`. We've already shown that at the very least, the `enqueueLinks()` function needs two arguments. The source, in our case the `$` object, and the destination - the `requestQueue`. To filter links, we need to add a third argument: `pseudoUrls`.
The `options.pseudoUrls` argument is always an `Array`, but its contents can take on many forms. [See the reference](../api/utils#utils.enqueueLinks) for all of them. Since we just need to filter out same domain links, we'll keep it simple and use a pseudo-URL `string`.
@@ -511,7 +571,7 @@ The `options.pseudoUrls` argument is always an `Array`, but its contents can tak
const options = {
$,
requestQueue,
- pseudoUrls: ['http[s?]://apify.com[.*]']
+ pseudoUrls: ["http[s?]://apify.com[.*]"]
};
await enqueueLinks(options);
@@ -542,8 +602,8 @@ Browsers handle this automatically, but since we're only using plain HTTP reques
const options = {
$,
requestQueue,
- pseudoUrls: ['http[s?]://apify.com[.*]'],
- baseUrl: request.loadedUrl,
+ pseudoUrls: ["http[s?]://apify.com[.*]"],
+ baseUrl: request.loadedUrl
};
await enqueueLinks(options);
@@ -552,73 +612,81 @@ await enqueueLinks(options);
> Even though it seems possible, we can't use the `request.url` of our `Request` instances, because the page could have been redirected and the final URL would be different from the one we requested.
#### Integrating `enqueueLinks()` into our crawler
+
That was fairly easy, wasn't it. That ticks the number 2 off our list and we're done! Let's take a look at the original crawler code, where we enqueued all the links manually.
```js
-const { URL } = require('url'); // <------ This is new.
-const Apify = require('apify');
+const { URL } = require("url"); // <------ This is new.
+const Apify = require("apify");
Apify.main(async () => {
const requestQueue = await Apify.openRequestQueue();
- await requestQueue.addRequest({ url: 'https://apify.com' });
-
+ await requestQueue.addRequest({ url: "https://apify.com" });
+
const handlePageFunction = async ({ request, $ }) => {
- const title = $('title').text();
+ const title = $("title").text();
console.log(`The title of "${request.url}" is: ${title}.`);
-
+
// Here starts the new part of handlePageFunction.
- const links = $('a[href]').map((i, el) => $(el).attr('href')).get();
+ const links = $("a[href]")
+ .map((i, el) => $(el).attr("href"))
+ .get();
- const ourDomain = 'https://apify.com';
+ const ourDomain = "https://apify.com";
const absoluteUrls = links.map(link => new URL(link, ourDomain));
- const sameDomainLinks = absoluteUrls.filter(url => url.href.startsWith(ourDomain));
-
+ const sameDomainLinks = absoluteUrls.filter(url =>
+ url.href.startsWith(ourDomain)
+ );
+
console.log(`Enqueueing ${sameDomainLinks.length} URLs.`);
for (const url of sameDomainLinks) {
await requestQueue.addRequest({ url: url.href });
}
};
-
+
const crawler = new Apify.CheerioCrawler({
maxRequestsPerCrawl: 20, // <------ This is new too.
requestQueue,
handlePageFunction
});
-
+
await crawler.run();
});
```
+
Since we've already prepared the `enqueueLinks()` options, we can just replace all the above enqueuing logic with a single function call, as promised.
```js
-const Apify = require('apify');
-const { utils: { enqueueLinks } } = Apify;
+const Apify = require("apify");
+const {
+ utils: { enqueueLinks }
+} = Apify;
Apify.main(async () => {
const requestQueue = await Apify.openRequestQueue();
- await requestQueue.addRequest({ url: 'https://apify.com' });
-
+ await requestQueue.addRequest({ url: "https://apify.com" });
+
const handlePageFunction = async ({ request, $ }) => {
- const title = $('title').text();
+ const title = $("title").text();
console.log(`The title of "${request.url}" is: ${title}.`);
-
+
// Enqueue links
const enqueued = await enqueueLinks({
$,
requestQueue,
- pseudoUrls: ['http[s?]://apify.com[.*]'],
- baseUrl: request.loadedUrl,
+ pseudoUrls: ["http[s?]://apify.com[.*]"],
+ baseUrl: request.loadedUrl
});
console.log(`Enqueued ${enqueued.length} URLs.`);
};
-
+
const crawler = new Apify.CheerioCrawler({
maxRequestsPerCrawl: 20,
requestQueue,
handlePageFunction
});
-
+
await crawler.run();
});
```
@@ -628,6 +696,7 @@ And that's it! No more parsing the links from HTML using Cheerio, filtering them
`Apify.utils.enqueueLinks()` has a lot more tricks up its sleeve. Make sure to check out the [reference documentation](../api/utils#utils.enqueueLinks) to see what else it can do for you. Namely the feature to prepopulate the `Request` instances it creates with `userData` of your choice is extremely useful!
## Getting some real world data
+
> Hey, guys, you know, it's cool that we can scrape the `<title>` elements of web pages, but that's not very useful. Can we finally scrape some real data and save it somewhere in a machine readable format? Because that's why started reading this tutorial in the first place!
We hear you young padawan! First, learn how to crawl, you must. Only then, save data, you can!
@@ -636,29 +705,33 @@ We hear you young padawan! First, learn how to crawl, you must. Only then, save
Fortunately, we don't have to travel to a galaxy far far away to find a good candidate for learning how to scrape structured data. The <a href="https://apify.com/store" target="_blank">Apify Store</a> is a store of public actors that anyone can grab and use. You can find ready-made solutions for crawling <a href="https://apify.com/drobnikj/crawler-google-places" target="_blank">Google Places</a>, <a href="https://apify.com/vaclavrut/amazon-crawler" target="_blank">Amazon</a>, <a href="https://apify.com/apify/google-search-scraper" target="_blank">Google Search</a>, <a href="https://apify.com/petr_cermak/booking-scraper" target="_blank">Booking</a>, <a href="https://apify.com/jaroslavhejlek/instagram-scraper" target="_blank">Instagram</a>, <a href="https://apify.com/petrpatek/tripadvisor-scraper" target="_blank">Tripadvisor</a> and many other websites. Feel free to check them out! It also poses a great place to practice our jedi scraping skills since it has categories, lists and details. That's almost like our imaginary `online-store.com` from the previous chapter.
### The importance of having a plan
+
Sometimes scraping is really straightforward, but most of the times, it really pays out to do a little bit of research first. How is the website structured? Can I scrape it only with HTTP requests (read "with `CheerioCrawler`") or would I need a full browser solution? Are there any anti-scraping protections in place? Do I need to parse the HTML or can I get the data otherwise, such as directly from the website's API. Jakub, one of Apify's founders wrote a <a href="https://blog.apify.com/web-scraping-in-2018-forget-html-use-xhrs-metadata-or-javascript-variables-8167f252439c" target="_blank">great article about all the different techniques</a> and tips and tricks so make sure to check that out!
For the purposes of this tutorial, let's just go ahead with HTTP requests and HTML parsing using `CheerioCrawler`. The number one reason being: We already know how to use it and we want to build on that knowledge to learn specific crawling and scraping techniques.
#### Choosing the data we need
-A good first step is always to figure out what it is we want to scrape and where to find it. For the time being, let's just agree that we want to scrape all actors (see the `Show` dropdown) in all categories (which can be found on the left side of the page) and for each actor we want to get its
-
- 1. URL
- 2. Owner
- 3. Unique identifier (such as `apify/web-scraper`)
- 4. Title
- 5. Description
- 6. Last run date
- 7. Number of runs
-
+
+A good first step is always to figure out what it is we want to scrape and where to find it. For the time being, let's just agree that we want to scrape all actors (see the `Show` dropdown) in all categories (which can be found on the left side of the page) and for each actor we want to get its
+
+1. URL
+2. Owner
+3. Unique identifier (such as `apify/web-scraper`)
+4. Title
+5. Description
+6. Last run date
+7. Number of runs
+
We can see that some of the information is available directly on the list page, but for details such as "Last run date" or "Number of runs" we'll need to open the actor detail pages too.
![data to scrape](/img/getting-started/scraping-practice.png "Overview of data to be scraped.")
#### Analyzing the target
+
Knowing that we will use plain HTTP requests, we immediately know that we won't be able to manipulate the website in any way. We will only be able to go through the HTML it gives us and parse our data from there. This might sound like a huge limitation, but you might be surprised in how effective it might be. Let's get on it!
#### The start URL(s)
+
This is where we start our crawl. It's convenient to start as close to our data as possible. For example, it wouldn't make much sense to start at `apify.com` and look for a `store` link there, when we already know that everything we want to extract can be found at the `apify.com/store` page.
Once we look at the `apify.com/store` page more carefully though, we see that the categories themselves produce URLs that we can use to access those individual categories.
@@ -682,9 +755,11 @@ https://apify.com/store?type=acts&category=TRAVEL
https://apify.com/store?type=acts&category=ECOMMERCE
https://apify.com/store?type=acts&category=ENTERTAINMENT
```
+
> The `type=acts` query parameter comes from selecting `Actors only` in the `Show` dropdown. This is in line with us only wanting to scrape actors' data. If you're wondering how we've created these URLs, simply visit the `https://apify.com/store` page, select `Actors only` in the `Show` dropdown and click on one of the categories in the left hand menu. The correct URL will show up in your browser's address bar.
### The crawling strategy
+
Now that we know where to start, we need to figure out where to go next. Since we've eliminated one level of crawling by selecting the categories manually, we only need to crawl the actor detail pages now. The algorithm therefore follows:
1. Visit the category list page (one of our start URLs).
@@ -697,16 +772,17 @@ Now that we know where to start, we need to figure out where to go next. Since w
`CheerioCrawler` will make sure to visit the pages for us, if we provide the correct `Requests` and we already know how to enqueue pages, so this should be fairly easy. Nevertheless, there are two more tricks that we'd like to show you.
#### Using a `RequestList`
+
`RequestList` is a perfect tool for scraping a pre-existing list of URLs and if you think about our start URLs, this is exactly what we have! A list of links to the different categories of the store. Let's see how we'd get them into a `RequestList`.
```js
const sources = [
- 'https://apify.com/store?type=acts&category=TRAVEL',
- 'https://apify.com/store?type=acts&category=ECOMMERCE',
- 'https://apify.com/store?type=acts&category=ENTERTAINMENT'
+ "https://apify.com/store?type=acts&category=TRAVEL",
+ "https://apify.com/store?type=acts&category=ECOMMERCE",
+ "https://apify.com/store?type=acts&category=ENTERTAINMENT"
];
-const requestList = await Apify.openRequestList('categories', sources);
+const requestList = await Apify.openRequestList("categories", sources);
```
As you can see, similarly to the `Apify.openRequestQueue()` function, there is an `Apify.openRequestList()` function that will create a `RequestList` instance for you. The first argument is a name of the `RequestList`. It is used to persist the crawling state of the list. This is useful when you want to continue where you left off after an error or a process restart. The second argument is the `sources` array, which is nothing more than a list of URLs you wish to crawl.
@@ -715,8 +791,8 @@ As you can see, similarly to the `Apify.openRequestQueue()` function, there is a
You might now want to ask one of the below questions:
- - Can I enqueue into `RequestList` too?
- - How do I make `RequestList` work together with `RequestQueue` since I need the queue to enqueue new `Requests`.
+- Can I enqueue into `RequestList` too?
+- How do I make `RequestList` work together with `RequestQueue` since I need the queue to enqueue new `Requests`.
The answer to the first one is a definitive no. `RequestList` is immutable and once you create it, you cannot add or remove `Requests` from it. The answer to the second one is simple. `RequestList` and `RequestQueue` are made to work together out of the box in crawlers, so all you need to do is use them both and the crawlers will do the rest.
@@ -727,6 +803,7 @@ const crawler = new Apify.CheerioCrawler({
handlePageFunction
});
```
+
> For those wondering how this works, the `RequestList` `Requests` are enqueued into the `RequestQueue` right before their execution and only processed by the `RequestQueue` afterwards. You can, of course, enqueue the `Requests` to the queue manually, but that would take some boilerplate code and perhaps quite a long time, if we were talking about tens of thousands or more `Requests`. The crawlers do it while running, so the time to enqueue is spread out and you won't even notice it.
#### Sanity check
@@ -735,43 +812,46 @@ It's always useful to create some simple boilerplate code to see that we've got
Let's use the newly acquired `RequestList` knowledge and everything we know from the previous chapters to create a new crawler that'll just visit all the category URLs we selected and print the text content of all the actors in the category. Try running the code below in your selected environment. You should see, albeit very badly formatted, the text of the individual actor cards that are displayed in the selected categories.
```js
-const Apify = require('apify');
+const Apify = require("apify");
Apify.main(async () => {
-
const sources = [
- 'https://apify.com/store?type=acts&category=TRAVEL',
- 'https://apify.com/store?type=acts&category=ECOMMERCE',
- 'https://apify.com/store?type=acts&category=ENTERTAINMENT'
+ "https://apify.com/store?type=acts&category=TRAVEL",
+ "https://apify.com/store?type=acts&category=ECOMMERCE",
+ "https://apify.com/store?type=acts&category=ENTERTAINMENT"
];
- const requestList = await Apify.openRequestList('categories', sources);
+ const requestList = await Apify.openRequestList("categories", sources);
const crawler = new Apify.CheerioCrawler({
requestList,
handlePageFunction: async ({ $, request }) => {
- $('.item').each((i, el) => { // <---- Select all the actor cards.
+ $(".item").each((i, el) => {
+ // <---- Select all the actor cards.
const text = $(el).text();
console.log(`ITEM: ${text}\n`);
- })
+ });
}
});
await crawler.run();
});
```
+
> If there's anything you don't understand, refer to the previous chapters on setting up your environment, building your first crawler and `CheerioCrawler`.
You might be wondering how we got that `.item` selector. After analyzing the category pages using a browser's DevTools, we've determined that it's a good selector to select all the currently displayed actor cards. DevTools and CSS selectors are quite a large topic, so we can't go into too much detail here, but here are a few general pointers.
#### DevTools crash course
+
> We'll use Chrome DevTools here, since it's the most common browser, but feel free to use any other, it's all very similar.
-At time of this writing, there are only 2 actors in the Travel category, so we'll use this one for our examples, since it will make everything much less cluttered. Now, go to
+At time of this writing, there are only 2 actors in the Travel category, so we'll use this one for our examples, since it will make everything much less cluttered. Now, go to
```
https://apify.com/store?type=acts&category=TRAVEL
```
+
and open DevTools either by right clicking anywhere in the page and selecting `Inspect`, or by pressing `F12` or by any other means relevant to your system. Once you're there, you'll see a bunch of DevToolsy stuff and a view of the category page with the individual actor cards.
Now, find the `Select an element` tool and use it to select one of the actor cards. Make sure to select the whole card, not some of its contents, such as its title or description.
@@ -787,22 +867,24 @@ It should now make sense how we got that `.item` selector. It's just a selector
It's always a good idea to double check that though, so go into the DevTools Console and run
```js
-document.querySelectorAll('.item');
+document.querySelectorAll(".item");
```
You will see that only the actor cards will be returned, and nothing else.
#### Enqueueing the detail links using a custom selector
+
In the previous chapter, we've used the `Apify.utils.enqueueLinks()` function like this:
```js
await enqueueLinks({
$,
requestQueue,
- pseudoUrls: ['http[s?]://apify.com[.*]'],
- baseUrl: request.loadedUrl,
+ pseudoUrls: ["http[s?]://apify.com[.*]"],
+ baseUrl: request.loadedUrl
});
```
+
While very useful in that scenario, we need something different now. Instead of finding all the `<a href="..">` links that match the `pseudoUrl`, we need to find only the specific ones that will take us to the actor detail pages. Otherwise, we'd be visiting a lot of other pages that we're not interested in. Using the power of DevTools and yet another `enqueueLinks()` parameter, this becomes fairly easy.
```js
@@ -814,44 +896,47 @@ const handlePageFunction = async ({ $, request }) => {
await Apify.utils.enqueueLinks({
$,
requestQueue,
- selector: 'a.item',
+ selector: "a.item",
baseUrl: request.loadedUrl,
userData: {
detailPage: true
}
});
}
-}
+};
```
The code should look pretty familiar to you. It's a very simple `handlePageFunction` where we log the currently processed URL to the console and enqueue more links. But there are also a few new, interesting additions. Let's break it down.
##### The `selector` parameter of `enqueueLinks()`
+
When we previously used `enqueueLinks()`, we were not providing any `selector` parameter and it was fine, because we wanted to use the default setting, which is `a` - finds all `<a>` elements. But now, we need to be more specific. There are multiple `<a>` links on the given category page, but we're only interested in those that will take us to item (actor) details. Using the DevTools, we found out that we can select the links we wanted using the `a.item` selector, which selects all the `<a class="item ...">` elements. And those are exactly the ones we're interested in.
##### The missing `pseudoUrls`
+
Earlier we've learned that `pseudoUrls` are not required and if omitted, all links matching the given `selector` will be enqueued. This is exactly what we need, so we're skipping `pseudoUrls` this time. That does not mean that you can't use `pseudoUrls` together with a custom `selector` though, because you absolutely can!
##### Finally, the `userData` of `enqueueLinks()`
+
You will see `userData` used often throughout Apify SDK and it's nothing more than a place to store your own data on a `Request` instance. You can access it by `request.userData` and it's a plain `Object` that can be used to store anything that needs to survive the full life-cycle of the `Request`.
Using the `userData` parameter of `enqueueLinks()` will populate all the `Request` instances it creates and enqueues with the provided data. In our case, we use it to mark the enqueued `Requests` as a `detailPage` so that we can easily differentiate between the category pages and the detail pages.
#### Another sanity check
+
It's always good to work step by step. We have this new enqueueing logic in place and since the previous [Sanity check](#sanity-check) worked only with a `RequestList`, because we were not enqueueing anything so don't forget to add back the `RequestQueue` and `maxRequestsPerCrawl` limit. Let's test it out!
```js
-const Apify = require('apify');
+const Apify = require("apify");
Apify.main(async () => {
-
const sources = [
- 'https://apify.com/store?type=acts&category=TRAVEL',
- 'https://apify.com/store?type=acts&category=ECOMMERCE',
- 'https://apify.com/store?type=acts&category=ENTERTAINMENT'
+ "https://apify.com/store?type=acts&category=TRAVEL",
+ "https://apify.com/store?type=acts&category=ECOMMERCE",
+ "https://apify.com/store?type=acts&category=ENTERTAINMENT"
];
- const requestList = await Apify.openRequestList('categories', sources);
+ const requestList = await Apify.openRequestList("categories", sources);
const requestQueue = await Apify.openRequestQueue(); // <----------------
const crawler = new Apify.CheerioCrawler({
@@ -866,14 +951,13 @@ Apify.main(async () => {
await Apify.utils.enqueueLinks({
$,
requestQueue,
- selector: 'a.item',
+ selector: "a.item",
baseUrl: request.loadedUrl,
userData: {
detailPage: true
}
});
}
-
}
});
@@ -886,6 +970,7 @@ We've added the `handlePageFunction()` with the `enqueueLinks()` logic from the
This concludes our Crawling strategy section, because we have taught the crawler to visit all the pages we need. Let's continue with scraping the tasty data.
### Scraping data
+
At the beginning of this chapter, we've created a list of information we wanted to collect about the actors in the store. Let's review that and figure out ways to access it.
1. URL
@@ -895,26 +980,29 @@ At the beginning of this chapter, we've created a list of information we wanted
5. Description
6. Last run date
7. Number of runs
-
+
![data to scrape](/img/getting-started/scraping-practice.png "Overview of data to be scraped.")
#### Scraping the URL, Owner and Unique identifier
+
Some information is lying right there in front of us without even having to touch the actor detail pages. The `URL` we already have - the `request.url`. And by looking at it carefully, we realize that it already includes the `owner` and the `unique identifier` too. We can just split the `string` and be on our way then!
```js
// request.url = https://apify.com/apify/web-scraper
-const urlArr = request.url.split('/').slice(-2); // ['apify', 'web-scraper']
-const uniqueIdentifier = urlArr.join('/'); // 'apify/web-scraper'
+const urlArr = request.url.split("/").slice(-2); // ['apify', 'web-scraper']
+const uniqueIdentifier = urlArr.join("/"); // 'apify/web-scraper'
const owner = urlArr[0]; // 'apify'
```
> It's always a matter of preference, whether to store this information separately in the resulting dataset, or not. Whoever uses the dataset can easily parse the `owner` from the `URL`, so should we duplicate the data unnecessarily? Our opinion is that unless the increased data consumption would be too large to bear, it's always better to make the dataset as readable as possible. Someone might want to filter by `owner` for example and keeping only the `URL` in the dataset would make this complicated without using additional tools.
#### Scraping Title, Description, Last run date and Number of runs
+
Now it's time to add more data to the results. Let's open one of the actor detail pages in the Store, for example the [`apify/web-scraper`](https://apify.com/apify/web-scraper) page and use our DevTools-Fu to figure out how to get the title of the actor.
##### Title
+
![actor title](/img/getting-started/title-01.png "Finding actor title in DevTools.")
By using the element selector tool, we find out that the title is there under an `<h1>` tag, as titles should be. Maybe surprisingly, we find that there are actually two `<h1>` tags on the detail page. This should get us thinking. Is there any parent element that perhaps wraps all the information that we want to scrape? Yes, there is! The `<div class="wrap ...">` is a common ancestor to everything. So let's start by getting that element first.
@@ -927,45 +1015,55 @@ Using the search bar to find `div.wrap` in the DevTools reveals that it's not th
```js
// Using jQuery.
-const $wrapper = $('header div.wrap');
+const $wrapper = $("header div.wrap");
```
+
> Always make sure to use the DevTools to verify your scraping process and assumptions. It's faster than changing the crawler code all the time.
Getting the title should now be pretty easy. We know that it's in the `$wrapper` so we just need to find it there using `jQuery`:
```js
-const $wrapper = $('header div.wrap');
+const $wrapper = $("header div.wrap");
return {
- title: $wrapper.find('h1').text(),
+ title: $wrapper.find("h1").text()
};
```
##### Description
+
Getting the actor's description is a piece of cake. We already have the boilerplate ready, so all we need to do is add a new selection.
![actor description selector](/img/getting-started/description.png "Finding actor description in DevTools.")
```js
-const $wrapper = $('header div.wrap');
+const $wrapper = $("header div.wrap");
return {
- title: $wrapper.find('h1').text(),
- description: $wrapper.find('p').text(),
+ title: $wrapper.find("h1").text(),
+ description: $wrapper.find("p").text()
};
```
Getting the `lastRunDate` and `runCount` is not as straightforward as the previous items, but not to worry, it's still pretty simple.
##### Last run date
+
The DevTools tell us that the `lastRunDate` can be found in the second of the two `<time>` elements in the `$wrapper`.
![actor last run date selector](/img/getting-started/last-run-date.png "Finding actor last run date in DevTools.")
```js
-const $wrapper = $('header div.wrap');
+const $wrapper = $("header div.wrap");
return {
- title: $wrapper.find('h1').text(),
- description: $wrapper.find('p').text(),
- lastRunDate: new Date(Number($wrapper.find('time').eq(1).attr('datetime'))),
+ title: $wrapper.find("h1").text(),
+ description: $wrapper.find("p").text(),
+ lastRunDate: new Date(
+ Number(
+ $wrapper
+ .find("time")
+ .eq(1)
+ .attr("datetime")
+ )
+ )
};
```
@@ -974,15 +1072,28 @@ It might look a little too complex at first glance, but let me walk you through
But we would much rather see a readable date in our results, not a unix timestamp, so we need to convert it. Unfortunately the `new Date()` constructor will not accept a `string`, so we cast the `string` to a `number` using the `Number()` function before actually calling `new Date()`. Phew!
##### Run count
+
And so we're finishing up with the `runCount`. There's no specific element like `<time>`, so we need to create a complex selector and then do a transformation on the result.
```js
-const $wrapper = $('header div.wrap');
+const $wrapper = $("header div.wrap");
return {
- title: $wrapper.find('h1').text(),
- description: $wrapper.find('p').text(),
- lastRunDate: new Date(Number($wrapper.find('time').eq(1).attr('datetime'))),
- runCount: Number($wrapper.find('div.stats > span:nth-of-type(3)').text().match(/\d+/)[0]),
+ title: $wrapper.find("h1").text(),
+ description: $wrapper.find("p").text(),
+ lastRunDate: new Date(
+ Number(
+ $wrapper
+ .find("time")
+ .eq(1)
+ .attr("datetime")
+ )
+ ),
+ runCount: Number(
+ $wrapper
+ .find("div.stats > span:nth-of-type(3)")
+ .text()
+ .match(/\d+/)[0]
+ )
};
```
@@ -991,37 +1102,49 @@ The `div.stats > span:nth-of-type(3)` looks complicated, but it only reads that
And there we have it! All the data we needed in a single object. For the sake of completeness, let's add the properties we parsed from the URL earlier and we're good to go.
```js
-const urlArr = request.url.split('/').slice(-2);
-const $wrapper = $('header div.wrap');
+const urlArr = request.url.split("/").slice(-2);
+const $wrapper = $("header div.wrap");
const results = {
url: request.url,
- uniqueIdentifier: urlArr.join('/'),
+ uniqueIdentifier: urlArr.join("/"),
owner: urlArr[0],
- title: $wrapper.find('h1').text(),
- description: $wrapper.find('p').text(),
- lastRunDate: new Date(Number($wrapper.find('time').eq(1).attr('datetime'))),
- runCount: Number($wrapper.find('div.stats > span:nth-of-type(3)').text().match(/\d+/)[0]),
+ title: $wrapper.find("h1").text(),
+ description: $wrapper.find("p").text(),
+ lastRunDate: new Date(
+ Number(
+ $wrapper
+ .find("time")
+ .eq(1)
+ .attr("datetime")
+ )
+ ),
+ runCount: Number(
+ $wrapper
+ .find("div.stats > span:nth-of-type(3)")
+ .text()
+ .match(/\d+/)[0]
+ )
};
-console.log('RESULTS: ', results);
+console.log("RESULTS: ", results);
```
#### Trying it out (sanity check #3)
+
We have everything we need so just grab our newly created scraping logic, dump it into our original `handlePageFunction()` and see the magic!
```js
-const Apify = require('apify');
+const Apify = require("apify");
Apify.main(async () => {
-
const sources = [
- 'https://apify.com/store?type=acts&category=TRAVEL',
- 'https://apify.com/store?type=acts&category=ECOMMERCE',
- 'https://apify.com/store?type=acts&category=ENTERTAINMENT'
+ "https://apify.com/store?type=acts&category=TRAVEL",
+ "https://apify.com/store?type=acts&category=ECOMMERCE",
+ "https://apify.com/store?type=acts&category=ENTERTAINMENT"
];
- const requestList = await Apify.openRequestList('categories', sources);
+ const requestList = await Apify.openRequestList("categories", sources);
const requestQueue = await Apify.openRequestQueue();
const crawler = new Apify.CheerioCrawler({
@@ -1030,22 +1153,34 @@ Apify.main(async () => {
requestQueue,
handlePageFunction: async ({ $, request }) => {
console.log(`Processing ${request.url}`);
-
+
// This is our new scraping logic.
if (request.userData.detailPage) {
- const urlArr = request.url.split('/').slice(-2);
- const $wrapper = $('header div.wrap');
+ const urlArr = request.url.split("/").slice(-2);
+ const $wrapper = $("header div.wrap");
const results = {
url: request.url,
- uniqueIdentifier: urlArr.join('/'),
+ uniqueIdentifier: urlArr.join("/"),
owner: urlArr[0],
- title: $wrapper.find('h1').text(),
- description: $wrapper.find('p').text(),
- lastRunDate: new Date(Number($wrapper.find('time').eq(1).attr('datetime'))),
- runCount: Number($wrapper.find('div.stats > span:nth-of-type(3)').text().match(/\d+/)[0]),
+ title: $wrapper.find("h1").text(),
+ description: $wrapper.find("p").text(),
+ lastRunDate: new Date(
+ Number(
+ $wrapper
+ .find("time")
+ .eq(1)
+ .attr("datetime")
+ )
+ ),
+ runCount: Number(
+ $wrapper
+ .find("div.stats > span:nth-of-type(3)")
+ .text()
+ .match(/\d+/)[0]
+ )
};
- console.log('RESULTS', results);
+ console.log("RESULTS", results);
}
// Only enqueue new links from the category pages.
@@ -1053,14 +1188,13 @@ Apify.main(async () => {
await Apify.utils.enqueueLinks({
$,
requestQueue,
- selector: 'a.item',
+ selector: "a.item",
baseUrl: request.loadedUrl,
userData: {
detailPage: true
}
});
}
-
}
});
@@ -1073,6 +1207,7 @@ Apify.main(async () => {
When running the actor in an environment of your choice, you should see the crawled URLs and their scraped data printed to the console.
### Saving the scraped data
+
A data extraction job would not be complete without saving the data for later use and processing. We've come to the final and most difficult part of this chapter so make sure to pay attention very carefully!
First, replace the `console.log` call on line `35` with
@@ -1084,17 +1219,16 @@ await Apify.pushData(results);
and that's it. Unlike in the previous paragraph, I'm serious now. That's it, we're done. The final code therefore looks exactly like this:
```js
-const Apify = require('apify');
+const Apify = require("apify");
Apify.main(async () => {
-
const sources = [
- 'https://apify.com/store?type=acts&category=TRAVEL',
- 'https://apify.com/store?type=acts&category=ECOMMERCE',
- 'https://apify.com/store?type=acts&category=ENTERTAINMENT'
+ "https://apify.com/store?type=acts&category=TRAVEL",
+ "https://apify.com/store?type=acts&category=ECOMMERCE",
+ "https://apify.com/store?type=acts&category=ENTERTAINMENT"
];
- const requestList = await Apify.openRequestList('categories', sources);
+ const requestList = await Apify.openRequestList("categories", sources);
const requestQueue = await Apify.openRequestQueue();
const crawler = new Apify.CheerioCrawler({
@@ -1103,20 +1237,32 @@ Apify.main(async () => {
requestQueue,
handlePageFunction: async ({ $, request }) => {
console.log(`Processing ${request.url}`);
-
+
// This is our new scraping logic.
if (request.userData.detailPage) {
- const urlArr = request.url.split('/').slice(-2);
- const $wrapper = $('header div.wrap');
+ const urlArr = request.url.split("/").slice(-2);
+ const $wrapper = $("header div.wrap");
const results = {
url: request.url,
- uniqueIdentifier: urlArr.join('/'),
+ uniqueIdentifier: urlArr.join("/"),
owner: urlArr[0],
- title: $wrapper.find('h1').text(),
- description: $wrapper.find('p').text(),
- lastRunDate: new Date(Number($wrapper.find('time').eq(1).attr('datetime'))),
- runCount: Number($wrapper.find('div.stats > span:nth-of-type(3)').text().match(/\d+/)[0]),
+ title: $wrapper.find("h1").text(),
+ description: $wrapper.find("p").text(),
+ lastRunDate: new Date(
+ Number(
+ $wrapper
+ .find("time")
+ .eq(1)
+ .attr("datetime")
+ )
+ ),
+ runCount: Number(
+ $wrapper
+ .find("div.stats > span:nth-of-type(3)")
+ .text()
+ .match(/\d+/)[0]
+ )
};
await Apify.pushData(results);
}
@@ -1126,14 +1272,13 @@ Apify.main(async () => {
await Apify.utils.enqueueLinks({
$,
requestQueue,
- selector: 'a.item',
+ selector: "a.item",
baseUrl: request.loadedUrl,
userData: {
detailPage: true
}
});
}
-
}
});
@@ -1142,17 +1287,21 @@ Apify.main(async () => {
```
#### What's `Apify.pushData()`
+
[`Apify.pushData()`](../api/apify#apify.pushData) is a helper function that saves data to the default [`Dataset`](../api/dataset). `Dataset` is a storage designed to hold virtually unlimited amount of data in a format similar to a table. Each time you call `Apify.pushData()` a new row in the table is created, with the property names serving as column titles.
> Each actor run has one default `Dataset` so no need to initialize it or create an instance first. It just gets done automatically for you. You can also create named datasets at will.
#### Finding my saved data
+
It might not be perfectly obvious where the data we saved using the previous command went, so let's break it down by environment:
##### Dataset on the Apify Platform
+
Open any Run of your actor on the Platform and you will see a Dataset as one of the available tabs. Clicking on it will reveal basic information about the Dataset and a list of options that you can use to download your data. There are various formats such as JSON, XLSX or CSV available and there's also the possibility of downloading only Clean items, i.e. a filtered dataset with empty rows and hidden fields removed.
##### Local Dataset
+
Unless you changed the environment variables that Apify SDK uses locally, which would suggest that you knew what you were doing and you didn't need this tutorial anyway, you'll find your data in your local Apify Storage.
```
@@ -1164,11 +1313,13 @@ The above folder will hold all your saved data in numbered files, as they were p
> Unfortunately, the local datasets don't yet support the export in various formats functionality that the Platform Dataset page offers, so for the time being, we're stuck with JSON.
### Final touch
+
It may seem that the data are extracted and the actor is done, but honestly, this is just the beginning. For the sake of brevity, we've completely omitted error handling, proxies, debug logging, tests, documentation and other stuff that a reliable software should have. The good thing is, **error handling is mostly done by Apify SDK itself**, so no worries on that front, unless you need some custom magic.
Anyway, to spark some ideas, let's look at two more things. First, passing an input to the actor, which will enable us to change the categories we want to scrape without changing the source code itself! And then some refactoring, to show you how we reckon is preferable to structure and annotate actor code.
#### Meet the `INPUT`
+
`INPUT` is just a convention on how we call the actor's input. Because there's no magic in actors, just features, the `INPUT` is actually nothing more than a key in the default [`KeyValueStore`](../api/keyvaluestore) that's, by convention, used as input on Apify Platform. Also by convention, the `INPUT` is mostly expected to be of `Content-Type: application/json`.
We will not go into `KeyValueStore` details here, but for the sake of `INPUT` you need to remember that there is a function that helps you get it.
@@ -1186,17 +1337,13 @@ Running locally, you need to place an `INPUT.json` file in your default key valu
```
#### Use `INPUT` to seed our actor with categories
+
Currently we're using the full URLs of categories as sources, but it's quite obvious that we only need the final parameters, the rest of the URL is always the same. Knowing that, we can pass an array of those parameters on `INPUT` and build the URLs dynamically, which would allow us to scrape different categories without changing the source code. Let's get to it!
First, we set up our `INPUT`, either in the `INPUT` form of the actor on Apify Platform, or by creating an `INPUT.json` in our default key value store locally.
```json
-[
- "TRAVEL",
- "ECOMMERCE",
- "ENTERTAINMENT"
-]
-
+["TRAVEL", "ECOMMERCE", "ENTERTAINMENT"]
```
Once we have that, we can load it in the actor and populate the crawler's sources with it. In the following example, we're using the categories in the input to construct the category URLs and we're also passing custom `userData` to the sources. This means that the `Requests` that get created will automatically contain this `userData`.
@@ -1204,17 +1351,18 @@ Once we have that, we can load it in the actor and populate the crawler's source
```js
// ...
const input = await Apify.getInput();
-
+
const sources = input.map(category => ({
url: `https://apify.com/store?type=acts&category=${category}`,
userData: {
- label: 'CATEGORY'
+ label: "CATEGORY"
}
}));
-
-const requestList = await Apify.openRequestList('categories', sources);
+
+const requestList = await Apify.openRequestList("categories", sources);
// ...
```
+
The `userData.label` is also a convention that we've been using for quite some time to label different `Requests`. We know that this is a category URL so we `label` it `CATEGORY`. This way, we can easily make decisions in the `handlePageFunction` without having to inspect the URL itself.
We can then refactor the `if` clauses in the `handlePageFunction` to use the `label` for decision making. This does not make much sense for a crawler with only two different pages, because a simple `boolean` would suffice, but for pages with multiple different views, it becomes very useful.
@@ -1225,11 +1373,11 @@ But perhaps we should not stop at refactoring the `if` clauses. There are severa
In the following code we've made several changes.
- - Split the code into multiple files.
- - Added the `Apify.utils.log` and replaced `console.log` with it.
- - Added a `getSources()` function to encapsulate `INPUT` consumption.
- - Added a `createRouter()` function to make our routing cleaner, without nested `if` clauses.
- - Removed the `maxRequestsPerCrawl` limit.
+- Split the code into multiple files.
+- Added the `Apify.utils.log` and replaced `console.log` with it.
+- Added a `getSources()` function to encapsulate `INPUT` consumption.
+- Added a `createRouter()` function to make our routing cleaner, without nested `if` clauses.
+- Removed the `maxRequestsPerCrawl` limit.
> To create a multi-file actor on the Apify Platform, select **Multiple source files** in the **Type** dropdown on the **Source** screen.
@@ -1237,30 +1385,35 @@ In our `main.js` file, we place the general structure of the crawler:
```js
// main.js
-const Apify = require('apify');
-const tools = require('./tools');
-const { utils: { log } } = Apify;
+const Apify = require("apify");
+const tools = require("./tools");
+const {
+ utils: { log }
+} = Apify;
Apify.main(async () => {
- log.info('Starting actor.');
- const requestList = await Apify.openRequestList('categories', await tools.getSources());
+ log.info("Starting actor.");
+ const requestList = await Apify.openRequestList(
+ "categories",
+ await tools.getSources()
+ );
const requestQueue = await Apify.openRequestQueue();
const router = tools.createRouter({ requestQueue });
- log.debug('Setting up crawler.');
+ log.debug("Setting up crawler.");
const crawler = new Apify.CheerioCrawler({
requestList,
requestQueue,
- handlePageFunction: async (context) => {
+ handlePageFunction: async context => {
const { request } = context;
log.info(`Processing ${request.url}`);
await router(request.userData.label, context);
}
});
- log.info('Starting the crawl.');
+ log.info("Starting the crawl.");
await crawler.run();
- log.info('Actor finished.');
+ log.info("Actor finished.");
});
```
@@ -1268,76 +1421,94 @@ Then in a separate `tools.js`, we add our helper functions:
```js
// tools.js
-const Apify = require('apify');
-const routes = require('./routes');
-const { utils: { log } } = Apify;
+const Apify = require("apify");
+const routes = require("./routes");
+const {
+ utils: { log }
+} = Apify;
exports.getSources = async () => {
- log.debug('Getting sources.');
+ log.debug("Getting sources.");
const input = await Apify.getInput();
return input.map(category => ({
url: `https://apify.com/store?type=acts&category=${category}`,
userData: {
- label: 'CATEGORY'
+ label: "CATEGORY"
}
}));
-}
+};
-exports.createRouter = (globalContext) => {
+exports.createRouter = globalContext => {
return async function(routeName, requestContext) {
const route = routes[routeName];
if (!route) throw new Error(`No route for name: ${routeName}`);
log.debug(`Invoking route: ${routeName}`);
return route(requestContext, globalContext);
- }
-}
+ };
+};
```
And finally our routes in a separate `routes.js` file:
```js
// routes.js
-const Apify = require('apify');
-const { utils: { log } } = Apify;
+const Apify = require("apify");
+const {
+ utils: { log }
+} = Apify;
exports.CATEGORY = async ({ $, request }, { requestQueue }) => {
return Apify.utils.enqueueLinks({
$,
requestQueue,
- selector: 'a.item',
+ selector: "a.item",
baseUrl: request.loadedUrl,
userData: {
- label: 'DETAIL'
+ label: "DETAIL"
}
- })
-}
+ });
+};
exports.DETAIL = async ({ $, request }) => {
- const urlArr = request.url.split('/').slice(-2);
- const $wrapper = $('header div.wrap');
+ const urlArr = request.url.split("/").slice(-2);
+ const $wrapper = $("header div.wrap");
- log.debug('Scraping results.');
+ log.debug("Scraping results.");
const results = {
url: request.url,
- uniqueIdentifier: urlArr.join('/'),
+ uniqueIdentifier: urlArr.join("/"),
owner: urlArr[0],
- title: $wrapper.find('h1').text(),
- description: $wrapper.find('p').text(),
- lastRunDate: new Date(Number($wrapper.find('time').eq(1).attr('datetime'))),
- runCount: Number($wrapper.find('div.stats > span:nth-of-type(3)').text().match(/\d+/)[0]),
+ title: $wrapper.find("h1").text(),
+ description: $wrapper.find("p").text(),
+ lastRunDate: new Date(
+ Number(
+ $wrapper
+ .find("time")
+ .eq(1)
+ .attr("datetime")
+ )
+ ),
+ runCount: Number(
+ $wrapper
+ .find("div.stats > span:nth-of-type(3)")
+ .text()
+ .match(/\d+/)[0]
+ )
};
- log.debug('Pushing data to dataset.');
+ log.debug("Pushing data to dataset.");
await Apify.pushData(results);
-}
+};
```
Let us tell you a little bit more about the changes. We're hopeful that in the end, you'll agree that this structure makes the actor more readable and manageable.
#### Splitting your code into multiple files
+
It was not always the case, but now that Apify Platform has a multifile editor, there's no reason not to split your code into multiple files and keep your logic separate. Less code in a single file means less code you need to think about at any time, and that's a great thing!
#### Using `Apify.utils.log` instead of `console.log`
+
We wont go into great lengths here to talk about `utils.log` here, because you can read [it all in the documentation](../api/log), but there's just one thing that we need to stress: **log levels**.
`utils.log` enables you to use different log levels, such as `log.debug`, `log.info` or `log.warning`. It not only makes your log more readable, but it also allows selective turning off of some levels by either calling the `utils.log.setLevel()` function or by setting an `APIFY_LOG_LEVEL` variable. This is huge! Because you can now add a lot of debug logs in your actor, which will help you when something goes wrong and turn them on or off with a simple `INPUT` change, or by setting an environment variable.
@@ -1345,6 +1516,7 @@ We wont go into great lengths here to talk about `utils.log` here, because you c
The punch line? Use `Apify.utils.log` instead of `console.log` now and thank us later when something goes wrong!
#### Using a router to structure your crawling
+
At first, it might seem more readable using just a simple `if / else` statement to select different logic based on the crawled pages, but trust me, it becomes far less impressive when working with more than 2 different pages and it definitely starts to fall apart when the logic to handle each page spans tens or hundreds of lines of code.
It's a good practice in any programming to split your logic into bite sized chunks that are easy to read and reason about. Scrolling through a thousand line long `handlePageFunction()` where everything interacts with everything and variables can be used everywhere is not a beautiful thing to do and a pain to debug. That's why we prefer the separation of routes into a special file and with large routes, we would even suggest having one file per route.
diff --git a/docs/guides/getting_started_quick.md b/docs/guides/getting_started_quick.md
index 228e9cc06..fc9862f31 100644
--- a/docs/guides/getting_started_quick.md
+++ b/docs/guides/getting_started_quick.md
@@ -2,6 +2,7 @@
id: quickstart
title: Quick Start
---
+
The Apify SDK requires <a href="https://nodejs.org/en/" target="_blank">Node.js</a> 8 or later.
## Local stand-alone usage
@@ -13,26 +14,31 @@ npm install apify --save
```
Run the following example to perform a recursive crawl of a website using Puppeteer.
-For more examples showcasing various features of the Apify SDK,
+For more examples showcasing various features of the Apify SDK,
[see the Examples section of the documentation](../examples/basiccrawler).
```javascript
-const Apify = require('apify');
+const Apify = require("apify");
Apify.main(async () => {
const requestQueue = await Apify.openRequestQueue();
- await requestQueue.addRequest({ url: 'https://www.iana.org/' });
- const pseudoUrls = [new Apify.PseudoUrl('https://www.iana.org/[.*]')];
+ await requestQueue.addRequest({ url: "https://www.iana.org/" });
+ const pseudoUrls = [new Apify.PseudoUrl("https://www.iana.org/[.*]")];
const crawler = new Apify.PuppeteerCrawler({
requestQueue,
handlePageFunction: async ({ request, page }) => {
const title = await page.title();
console.log(`Title of ${request.url}: ${title}`);
- await Apify.utils.puppeteer.enqueueLinks({ page, selector: 'a', pseudoUrls, requestQueue });
+ await Apify.utils.puppeteer.enqueueLinks({
+ page,
+ selector: "a",
+ pseudoUrls,
+ requestQueue
+ });
},
maxRequestsPerCrawl: 100,
- maxConcurrency: 10,
+ maxConcurrency: 10
});
await crawler.run();
@@ -92,6 +98,7 @@ Now you can easily deploy your code to the Apify Cloud by running:
```bash
apify login
```
+
```bash
apify push
```
diff --git a/docs/guides/motivation.md b/docs/guides/motivation.md
index 644940b5d..1d742c779 100644
--- a/docs/guides/motivation.md
+++ b/docs/guides/motivation.md
@@ -8,12 +8,12 @@ Thanks to tools like <a href="https://github.com/GoogleChrome/puppeteer" target=
it is easy to write Node.js code to extract data from web pages.
But eventually things will get complicated. For example, when you try to:
-* Perform a deep crawl of an entire website using a persistent queue of URLs.
-* Run your scraping code on a list of 100k URLs in a CSV file,
- without losing any data when your code crashes.
-* Rotate proxies to hide your browser origin.
-* Schedule the code to run periodically and send notification on errors.
-* Disable browser fingerprinting protections used by websites.
+- Perform a deep crawl of an entire website using a persistent queue of URLs.
+- Run your scraping code on a list of 100k URLs in a CSV file,
+ without losing any data when your code crashes.
+- Rotate proxies to hide your browser origin.
+- Schedule the code to run periodically and send notification on errors.
+- Disable browser fingerprinting protections used by websites.
Python has <a href="https://scrapy.org/" target="_blank">Scrapy</a> for these tasks, but there was no
such library for **JavaScript, the language of the web**.
diff --git a/docs/guides/puppeteer_live_view.md b/docs/guides/puppeteer_live_view.md
index 3bfe6ec18..f282357a2 100644
--- a/docs/guides/puppeteer_live_view.md
+++ b/docs/guides/puppeteer_live_view.md
@@ -15,7 +15,7 @@ the `puppeteerPoolOptions` of [`PuppeteerCrawler`](../api/puppeteercrawler#new_P
```js
const crawler = new Apify.PuppeteerCrawler({
puppeteerPoolOptions: {
- useLiveView: true,
+ useLiveView: true
}
// other options
});
@@ -25,9 +25,9 @@ or directly to the [`PuppeteerPool`](../api/puppeteerpool) constructor, when usi
```js
const pool = new Apify.PuppeteerPool({
- useLiveView: true,
+ useLiveView: true
// other options
-})
+});
```
To simplify debugging, you may also want to add the
diff --git a/docs/guides/what_is_an_actor.md b/docs/guides/what_is_an_actor.md
index 979c6f9ab..28bea6064 100644
--- a/docs/guides/what_is_an_actor.md
+++ b/docs/guides/what_is_an_actor.md
@@ -2,6 +2,7 @@
id: whatisanactor
title: What is an Actor
---
+
When you deploy your script to the <a href="https://apify.com/" target="_blank">Apify Cloud</a>,
it becomes an actor.
An actor is a serverless microservice that accepts an input and produces an output.
@@ -17,7 +18,7 @@ and somebody uses it, it runs under their account, not yours.
**Related links**
-* <a href="https://apify.com/store?&type=acts" target="_blank">Store of existing actors</a>
-* <a href="https://apify.com/docs/actor" target="_blank">Documentation</a>
-* <a href="https://my.apify.com/actors" target="_blank">View actors in Apify app</a>
-* <a href="https://apify.com/docs/api/v2#/reference/actors" target="_blank">API reference</a>
+- <a href="https://apify.com/store?&type=acts" target="_blank">Store of existing actors</a>
+- <a href="https://apify.com/docs/actor" target="_blank">Documentation</a>
+- <a href="https://my.apify.com/actors" target="_blank">View actors in Apify app</a>
+- <a href="https://apify.com/docs/api/v2#/reference/actors" target="_blank">API reference</a>
diff --git a/docs/readme/introduction.md b/docs/readme/introduction.md
index 75834704a..41153fc6b 100644
--- a/docs/readme/introduction.md
+++ b/docs/readme/introduction.md
@@ -1,4 +1,5 @@
# Apify SDK: The scalable web crawling and scraping library for JavaScript
+
<!-- Mirror this part to src/index.js -->
[![npm version](https://badge.fury.io/js/apify.svg)](https://www.npmjs.com/package/apify)
diff --git a/docs/typedefs/ActorRun.md b/docs/typedefs/ActorRun.md
index 3e79ac0fa..e97b3c189 100644
--- a/docs/typedefs/ActorRun.md
+++ b/docs/typedefs/ActorRun.md
@@ -2,6 +2,7 @@
id: actorrun
title: ActorRun
---
+
<a name="ActorRun"></a>
Represents information about an actor run, as returned by the
@@ -14,6 +15,7 @@ For more details, see
<a href="https://apify.com/docs/actor#run" target="_blank">Runs.</a>
**Properties**
+
<table>
<thead>
<tr>
diff --git a/docs/typedefs/ApifyCallError.md b/docs/typedefs/ApifyCallError.md
index eeaa1fa4d..264b0491f 100644
--- a/docs/typedefs/ApifyCallError.md
+++ b/docs/typedefs/ApifyCallError.md
@@ -2,12 +2,14 @@
id: apifycallerror
title: ApifyCallError
---
+
<a name="ApifyCallError"></a>
The class represents exceptions thrown
by the [`Apify.call()`](../api/apify#module_Apify.call) function.
**Properties**
+
<table>
<thead>
<tr>
diff --git a/docs/typedefs/LaunchPuppeteerOptions.md b/docs/typedefs/LaunchPuppeteerOptions.md
index f8078d9d0..d54a773fe 100644
--- a/docs/typedefs/LaunchPuppeteerOptions.md
+++ b/docs/typedefs/LaunchPuppeteerOptions.md
@@ -2,6 +2,7 @@
id: launchpuppeteeroptions
title: LaunchPuppeteerOptions
---
+
<a name="LaunchPuppeteerOptions"></a>
Apify extends the launch options of Puppeteer.
@@ -11,6 +12,7 @@ options in the [`Apify.launchPuppeteer()`](../api/apify#module_Apify.launchPuppe
function and in addition, all the options available below.
**Properties**
+
<table>
<thead>
<tr>
diff --git a/docs/typedefs/QueueOperationInfo.md b/docs/typedefs/QueueOperationInfo.md
index b97676b45..435c10375 100644
--- a/docs/typedefs/QueueOperationInfo.md
+++ b/docs/typedefs/QueueOperationInfo.md
@@ -2,6 +2,7 @@
id: queueoperationinfo
title: QueueOperationInfo
---
+
<a name="QueueOperationInfo"></a>
A helper class that is used to report results from various
@@ -9,6 +10,7 @@ A helper class that is used to report results from various
[`Apify.utils.enqueueLinks()`](../api/utils#utils.enqueueLinks).
**Properties**
+
<table>
<thead>
<tr>
diff --git a/docs/typedefs/StealthOptions.md b/docs/typedefs/StealthOptions.md
index 4e3d311de..3355929e2 100644
--- a/docs/typedefs/StealthOptions.md
+++ b/docs/typedefs/StealthOptions.md
@@ -2,12 +2,14 @@
id: stealthoptions
title: StealthOptions
---
+
<a name="StealthOptions"></a>
Configuration of stealth tricks for a proper hiding effect all of them should be set to true.
These tricks are applied only when the `stealth` option is set to `true`.
**Properties**
+
<table>
<thead>
<tr>