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.

Build docs

Ondra Urbanb9b6249a4008
diff --git a/README.md b/README.md
index e39ae1d20..4d035383e 100644
--- a/README.md
+++ b/README.md
@@ -117,119 +117,203 @@ The Apify SDK is available as the <a href="https://www.npmjs.com/package/apify">
</ul>
## Getting Started
-The Apify SDK requires <a href="https://nodejs.org/en/" target="_blank">Node.js</a> 8 or later.
+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.
-### Local stand-alone usage
+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.
-Add Apify SDK to any Node.js project by running:
+### 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.
-```bash
-npm install apify --save
-```
+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.
-Run the following example to perform a recursive crawl of a website using Puppeteer.
-For more examples showcasing various features of the Apify SDK,
-[see the Examples section of the documentation](https://sdk.apify.com/docs/examples/basiccrawler).
+### Setting up locally
+To run Apify SDK on your own computer, you need to meet the following pre-requisites first:
-```javascript
-const Apify = require('apify');
+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>
+2. Have NPM installed.
+ * NPM comes bundled with Node.js so you should already have it. If not, reinstall Node.js.
-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/[.*]')];
+If you're not certain, confirm the pre-requisites by running:
- 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, 'a', pseudoUrls, requestQueue);
- },
- maxRequestsPerCrawl: 100,
- maxConcurrency: 10,
- });
+```bash
+node -v
+```
- await crawler.run();
-});
+```bash
+npm -v
```
-When you run the example, you should see Apify SDK automating a Chrome browser.
+#### Adding Apify SDK to an existing project
+Apify SDK can be added as a dependency into any Node.js project, so if you already have a project that you'd like to add web crawling, scraping and automation capabilities to, just run the following command in the project's folder and you're good to go.
+
+```bash
+npm install apify
+```
-![Chrome Scrape](https://sdk.apify.com/img/chrome_scrape.gif)
+#### Creating a new project
+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.
-By default, Apify SDK stores data to
-`./apify_storage` in the current working directory.
-You can override this behavior by setting either the
-`APIFY_LOCAL_STORAGE_DIR` or `APIFY_TOKEN` environment variable.
-For details, see [Environment variables](https://sdk.apify.com/docs/guides/environmentvariables)
-and [Data storage](https://sdk.apify.com/docs/guides/datastorage).
+Let's install the Apify CLI with the following command:
-### Local usage with Apify command-line interface (CLI)
+```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:
-To avoid the need to set the environment variables manually,
-to create a boilerplate of your project,
-and to enable pushing and running your code on the
-<a href="https://www.apify.com" target="_blank">Apify Cloud</a>,
-you can use the
-<a href="https://github.com/apifytech/apify-cli" target="_blank">Apify command-line interface</a>
-(CLI) tool.
+```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.
-Install the CLI by running:
+Let's try that!
```bash
-npm -g install apify-cli
+cd my-new-project
+```
+```bash
+apify run
```
-You might need to run the above command with `sudo`, depending on how crazy your configuration is.
+You should start seeing log messages in the terminal as the system boots up and after a second, a Chromium browser window should pop up. In the window, you'll see quickly changing pages and back in the terminal, you should see the titles (contents of the &lt;title&gt; HTML tags) of the pages printed.
-Now create a boilerplate of your new web crawling project by running:
+You can always terminate the crawl with a keypress in the terminal:
```bash
-apify create my-hello-world
+CTRL+C
```
+Did you see all that? If you did, congratulations! You're ready to go!
-The CLI will prompt you to select a project boilerplate template - just pick "Hello world".
-The tool will create a directory called `my-hello-world` with a Node.js project files.
-You can run the project as follows:
+### 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.
-```bash
-cd my-hello-world
-apify run
+The <a href="https://my.apify.com" target="_blank">Apify Platform</a> is the foundational product of <a href="https://www.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.
+
+It comes with a free account, so let's go to our
+<a href="https://my.apify.com/sign-up" target="_blank">sign-up page</a>
+and create one, if you haven't already. Don't forget to verify your email. Without it, you won't be able to run any projects.
+
+Once you're in, you might by 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. You might be tempted to go directly to Crawlers, because what the heck are **Actors**, right? Bear with me, **Actors** are the tool that you really want! To read more about them, see: [What is an Actor](https://sdk.apify.com/docs/guides/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.
+
+Good job. You're now ready to run your own source code on the Apify Platform. For more information visit the
+<a href="https://www.apify.com/docs/actor" target="_blank">Actor documentation page</a>,
+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`](https://sdk.apify.com/docs/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`](https://sdk.apify.com/docs/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`](https://sdk.apify.com/docs/api/request)%20object) that the crawler will visit, one by one, retrying whenever an error occurs, until there are no more `Requests` to process.
+
+[`RequestQueue`](https://sdk.apify.com/docs/api/requestqueue)%20on%20the%20other%20hand,%20represents%20a%20dynamic%20queue%20of%20%60Requests%60.%20One%20that%20can%20be%20updated%20at%20runtime%20by%20adding%20more%20pages%20-%20%60Requests%60%20to%20process.%20This%20allows%20the%20crawler%20to%20open%20one%20page,%20extract%20interesting%20URLs,%20such%20as%20links%20to%20other%20pages%20on%20the%20same%20domain,%20add%20them%20to%20the%20queue%20(called%20*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`](https://sdk.apify.com/docs/api/autoscaledpool) class and we'll talk about it in detail later.
+
+```js
+// The object received as a single argument by the handlePageFunction
+{
+ request: Request,
+ autoscaledPool: AutoscaledPool
+}
```
-By default, the crawling data will be stored in a local directory at `./apify_storage`.
-For example, the input JSON file for the actor is expected to be in the default key-value store
-in `./apify_storage/key_value_stores/default/INPUT.json`.
+#### 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()`](https://sdk.apify.com/docs/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.
-Now you can easily deploy your code to the Apify Cloud by running:
+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:
-```bash
-apify login
+```js
+const Apify = require('apify');
```
-```bash
-apify push
+
+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://www.apify.com" target="_blank">https://www.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');
+
+// 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://www.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()`](https://sdk.apify.com/docs/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://www.apify.com`. Now we need the `handlePageFunction`.
+
+```js
+// We'll define the function separately so it's more obvious.
+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();
+
+ 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');
+
+Apify.main(async () => {
+ const requestQueue = await Apify.openRequestQueue();
+ await requestQueue.addRequest({ url: 'https://www.apify.com' });
+
+ const handlePageFunction = async ({ request, $ }) => {
+ 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();
+});
```
-Your script will be uploaded to the Apify Cloud and built there so that it can be run.
-For more information, view the
-<a href="https://www.apify.com/docs/cli" target="_blank">Apify CLI</a>
-and
-<a href="https://www.apify.com/docs/actor" target="_blank">Apify Actor</a>
-documentation.
-
-### Usage on the Apify Cloud
-
-You can also develop your web scraping project
-in an online code editor directly on the
-<a href="https://www.apify.com" target="_blank">Apify Cloud</a>.
-You'll need to have an Apify Account.
-Go to <a href="https://my.apify.com/actors" target="_blank">Actors</a>,
-page in the app, click <i>Create new</i> and then go to the
-<i>Source</i> tab and start writing your code or paste one of the examples from the Examples section.
-
-For more information, view the
-<a href="https://www.apify.com/docs/actor#quick-start" target="_blank">Apify actors quick start guide</a>.
+And we're done! You just created your first crawler from scratch. It will download the HTML of `https://www.apify.com`, find the `<title>` element, get its text content and print it to console. Good job!
+
+To run the code locally, copy and paste the code, if you haven't already typed it in yourself, to the `main.js` file in the `my-new-project` we created earlier and run `apify run` from that project's directory.
+
+To run the code on Apify Platform, just replace the original example with your new code and hit Run.
+
+Whichever environment you choose, you should see the message `The title of "https://www.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` 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` comes in.
+
+
+> TO BE CONTINUED ...
## Support
diff --git a/docs/api/Apify.md b/docs/api/Apify.md
index 36a4bb705..6adc46dbd 100644
--- a/docs/api/Apify.md
+++ b/docs/api/Apify.md
@@ -24,6 +24,7 @@ accessible from the left sidebar.
* [`.main(userFunc)`](#module_Apify.main)
* [`.openDataset([datasetIdOrName], [options])`](#module_Apify.openDataset) ⇒ [<code>Promise&lt;Dataset&gt;</code>](dataset)
* [`.openKeyValueStore([storeIdOrName], [options])`](#module_Apify.openKeyValueStore) ⇒ [<code>Promise&lt;KeyValueStore&gt;</code>](keyvaluestore)
+ * [`.openRequestList`](#module_Apify.openRequestList) ⇒ [<code>Promise&lt;RequestList&gt;</code>](requestlist)
* [`.openRequestQueue`](#module_Apify.openRequestQueue) ⇒ [<code>Promise&lt;RequestQueue&gt;</code>](requestqueue)
* [`.pushData(item)`](#module_Apify.pushData) ⇒ <code>Promise</code>
* [`.setValue(key, value, [options])`](#module_Apify.setValue) ⇒ <code>Promise</code>
@@ -711,6 +712,66 @@ For more details and code examples, see the [`KeyValueStore`](keyvaluestore) cla
environment variable is set. This way it is possible to combine local and cloud storage.</p>
</td></tr></tbody>
</table>
+<a name="module_Apify.openRequestList"></a>
+
+## `Apify.openRequestList` ⇒ [<code>Promise&lt;RequestList&gt;</code>](requestlist)
+Opens a request list and returns a promise resolving to an instance
+of the [`RequestList`](requestlist) class that is already initialized.
+
+[`RequestList`](requestlist) represents a list of URLs to crawl, which is always stored in memory.
+To enable picking up where left off after a process restart, the request list sources
+are persisted to the key value store at initialization of the list. Then, while crawling,
+a small state object is regularly persisted to keep track of the crawling status.
+
+For more details and code examples, see the [`RequestList`](requestlist) class.
+
+**Example Usage:**
+
+```javascript
+const sources = [
+ 'https://www.example.com',
+ 'https://www.google.com',
+ 'https://www.bing.com'
+];
+
+const requestList = await Apify.openRequestList('my-name', sources);
+```
+
+<table>
+<thead>
+<tr>
+<th>Param</th><th>Type</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td><code>listName</code></td><td><code>string</code> | <code>null</code></td>
+</tr>
+<tr>
+<td colspan="3"><p>Name of the request list to be opened. Setting a name enables the <code>RequestList</code>&#39;s state to be persisted
+ in the key value store. This is useful in case of a restart or migration. Since <code>RequestList</code> is only
+ stored in memory, a restart or migration wipes it clean. Setting a name will enable the <code>RequestList</code>&#39;s
+ state to survive those situations and continue where it left off.</p>
+<p> The name will be used as a prefix in key value store, producing keys such as <code>NAME-REQUEST_LIST_STATE</code>
+ and <code>NAME-REQUEST_LIST_SOURCES</code>.</p>
+<p> If <code>null</code>, the list will not be persisted and will only be stored in memory. Process restart
+ will then cause the list to be crawled again from the beginning. We suggest always using a name.</p>
+</td></tr><tr>
+<td><code>sources</code></td><td><code>Array&lt;Object&gt;</code> | <code>Array&lt;string&gt;</code></td>
+</tr>
+<tr>
+<td colspan="3"><p>Sources represent the URLs to crawl. It can either be a <code>string[]</code> with plain URLs or an <code>Object[]</code>.
+ The objects&#39; contents can either be just plain objects, defining at least the &#39;url&#39; property
+ or instances of the <a href="request"><code>Request</code></a> class. See the (<code>new RequestList</code>)(RequestList#new_RequestList_new)
+ options for details.</p>
+</td></tr><tr>
+<td><code>[options]</code></td><td><code>Object</code></td>
+</tr>
+<tr>
+<td colspan="3"><p>The (<code>new RequestList</code>)(RequestList#new_RequestList_new) options. Note that the listName parameter supersedes
+ the <code>persistStateKey</code> and <code>persistSourcesKey</code> options and the sources parameter supersedes the <code>sources</code> option.</p>
+</td></tr></tbody>
+</table>
<a name="module_Apify.openRequestQueue"></a>
## `Apify.openRequestQueue` ⇒ [<code>Promise&lt;RequestQueue&gt;</code>](requestqueue)
diff --git a/docs/api/AutoscaledPool.md b/docs/api/AutoscaledPool.md
index d8989ff5b..e4f771bf1 100644
--- a/docs/api/AutoscaledPool.md
+++ b/docs/api/AutoscaledPool.md
@@ -57,6 +57,8 @@ await pool.run();
* [`.setMinConcurrency(minConcurrency)`](#AutoscaledPool+setMinConcurrency)
* [`.run()`](#AutoscaledPool+run) ⇒ <code>Promise</code>
* [`.abort()`](#AutoscaledPool+abort) ⇒ <code>Promise</code>
+ * [`.pause([timeoutSecs])`](#AutoscaledPool+pause) ⇒ <code>Promise</code>
+ * [`.resume()`](#AutoscaledPool+resume)
<a name="new_AutoscaledPool_new"></a>
@@ -208,5 +210,47 @@ all the tasks are finished or one of them fails.
<a name="AutoscaledPool+abort"></a>
## `autoscaledPool.abort()` ⇒ <code>Promise</code>
-Aborts the run of the auto-scaled pool, discards all currently running tasks and destroys it.
+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.
+
+Due to the nature of the tasks, auto-scaled pool cannot reliably guarantee abortion
+of all the running tasks, therefore, no abortion is attempted and some of the tasks
+may finish, while others may not. Essentially, auto-scaled pool doesn't care about
+their state after the invocation of `.abort()`, but that does not mean that some
+parts of their asynchronous chains of commands will not execute.
+
+<a name="AutoscaledPool+pause"></a>
+
+## `autoscaledPool.pause([timeoutSecs])` ⇒ <code>Promise</code>
+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)
+
+The function's promise will resolve once all running tasks have completed and the pool
+is effectively idle. If the `timeoutSecs` argument is provided, the promise will reject
+with a timeout error after the `timeoutSecs` seconds.
+
+The promise returned from the [`run()`](#AutoscaledPool+run) function will not resolve
+when `.pause()` is invoked (unlike abort, which resolves it).
+
+<table>
+<thead>
+<tr>
+<th>Param</th><th>Type</th>
+</tr>
+</thead>
+<tbody>
+<tr>
+<td><code>[timeoutSecs]</code></td><td><code>number</code></td>
+</tr>
+<tr>
+</tr></tbody>
+</table>
+<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 1e36308a9..bc666712f 100644
--- a/docs/api/BasicCrawler.md
+++ b/docs/api/BasicCrawler.md
@@ -60,7 +60,6 @@ await crawler.run();
* [BasicCrawler](basiccrawler)
* [`new BasicCrawler(options)`](#new_BasicCrawler_new)
* [`.run()`](#BasicCrawler+run) ⇒ <code>Promise</code>
- * [`.abort()`](#BasicCrawler+abort) ⇒ <code>Promise</code>
<a name="new_BasicCrawler_new"></a>
@@ -85,7 +84,8 @@ await crawler.run();
<td colspan="3"><p>User-provided function that performs the logic of the crawler. It is called for each URL to crawl.</p>
<p> The function receives the following object as an argument:</p>
<pre><code>{
- request: Request
+ request: Request,
+ autoscaledPool: AutoscaledPool
}
</code></pre><p> where the <a href="request"><code>Request</code></a> instance represents the URL to crawl.</p>
<p> The function must return a promise, which is then awaited by the crawler.</p>
@@ -161,8 +161,3 @@ await crawler.run();
## `basicCrawler.run()` ⇒ <code>Promise</code>
Runs the crawler. Returns a promise that gets resolved once all the requests are processed.
-<a name="BasicCrawler+abort"></a>
-
-## `basicCrawler.abort()` ⇒ <code>Promise</code>
-Aborts the crawler by preventing additional requests and terminating the running ones.
-
diff --git a/docs/api/CheerioCrawler.md b/docs/api/CheerioCrawler.md
index c67647c3f..38bc3e200 100644
--- a/docs/api/CheerioCrawler.md
+++ b/docs/api/CheerioCrawler.md
@@ -71,7 +71,6 @@ await crawler.run();
* [CheerioCrawler](cheeriocrawler)
* [`new CheerioCrawler(options)`](#new_CheerioCrawler_new)
* [`.run()`](#CheerioCrawler+run) ⇒ <code>Promise</code>
- * [`.abort()`](#CheerioCrawler+abort) ⇒ <code>Promise</code>
<a name="new_CheerioCrawler_new"></a>
@@ -100,7 +99,8 @@ await crawler.run();
$: Cheerio, // the Cheerio object with parsed HTML
html: String // the raw HTML of the page
request: Request,
- response: Object // An instance of Node&#39;s http.IncomingMessage object
+ response: Object // An instance of Node&#39;s http.IncomingMessage object,
+ autoscaledPool: AutoscaledPool
}
</code></pre><p> With the <a href="request"><code>Request</code></a> object representing the URL to crawl.</p>
<p> If the function returns a promise, it is awaited by the crawler.</p>
@@ -215,7 +215,9 @@ await crawler.run();
<tr>
<td colspan="3"><p>Custom options passed to the underlying <a href="autoscaledpool"><code>AutoscaledPool</code></a> constructor.
Note that the <code>runTaskFunction</code>, <code>isTaskReadyFunction</code> and <code>isFinishedFunction</code> options
- are provided by <code>CheerioCrawler</code> and cannot be overridden.</p>
+ are provided by <code>CheerioCrawler</code> and cannot be overridden. Reasonable <a href="snapshotter"><code>Snapshotter</code></a>
+ and <a href="systemstatus"><code>SystemStatus</code></a> defaults are provided to account for the fact that <code>cheerio</code>
+ parses HTML synchronously and therefore blocks the event loop.</p>
</td></tr><tr>
<td><code>[options.minConcurrency]</code></td><td><code>Object</code></td><td><code>1</code></td>
</tr>
@@ -235,8 +237,3 @@ await crawler.run();
## `cheerioCrawler.run()` ⇒ <code>Promise</code>
Runs the crawler. Returns promise that gets resolved once all the requests got processed.
-<a name="CheerioCrawler+abort"></a>
-
-## `cheerioCrawler.abort()` ⇒ <code>Promise</code>
-Aborts the crawler by preventing crawls of additional pages and terminating the running ones.
-
diff --git a/docs/api/PuppeteerCrawler.md b/docs/api/PuppeteerCrawler.md
index 540ebe024..a46437107 100644
--- a/docs/api/PuppeteerCrawler.md
+++ b/docs/api/PuppeteerCrawler.md
@@ -63,7 +63,6 @@ await crawler.run();
* [PuppeteerCrawler](puppeteercrawler)
* [`new PuppeteerCrawler(options)`](#new_PuppeteerCrawler_new)
* [`.run()`](#PuppeteerCrawler+run) ⇒ <code>Promise</code>
- * [`.abort()`](#PuppeteerCrawler+abort) ⇒ <code>Promise</code>
<a name="new_PuppeteerCrawler_new"></a>
@@ -91,7 +90,8 @@ await crawler.run();
request: Request,
response: Response,
page: Page,
- puppeteerPool: PuppeteerPool
+ puppeteerPool: PuppeteerPool,
+ autoscaledPool: AutoscaledPool
}
</code></pre><p> <code>request</code> is an instance of the <a href="request"><code>Request</code></a> object with details about the URL to open, HTTP method etc.
<code>response</code> is an instance of the <code>Puppeteer</code>
@@ -243,8 +243,3 @@ await crawler.run();
## `puppeteerCrawler.run()` ⇒ <code>Promise</code>
Runs the crawler. Returns promise that gets resolved once all the requests got processed.
-<a name="PuppeteerCrawler+abort"></a>
-
-## `puppeteerCrawler.abort()` ⇒ <code>Promise</code>
-Aborts the crawler by preventing crawls of additional pages and terminating the running ones.
-
diff --git a/docs/api/RequestList.md b/docs/api/RequestList.md
index 93edee208..303c8b01c 100644
--- a/docs/api/RequestList.md
+++ b/docs/api/RequestList.md
@@ -22,10 +22,18 @@ and [`PuppeteerCrawler`](puppeteercrawler) as a source of URLs to crawl.
Unlike [`RequestQueue`](requestqueue), `RequestList` is static but it can contain even millions of URLs.
`RequestList` has an internal state where it stores information about which requests were already handled,
-which are in progress and which were reclaimed. The state might be automatically persisted to the default
-key-value store by setting the `persistStateKey` option o that if the Node.js process is restarted,
+which are in progress and which were reclaimed. The state may be automatically persisted to the default
+key-value store by setting the `persistStateKey` option so that if the Node.js process is restarted,
the crawling can continue where it left off. For more details, see [`KeyValueStore`](keyvaluestore).
+The internal state is closely tied to the provided sources (URLs) to validate it's position in the list
+after a migration or restart. Therefore, if the sources change, the state will become corrupted and
+`RequestList` will raise an exception. This typically happens when using a live list of URLs downloaded
+from the internet as sources. Either from some service's API, or using the `requestsFromUrl` option.
+If that's your case, please use the `persistSourcesKey` option in conjunction with `persistStateKey`,
+it will persist the initial sources to the default key-value store and load them after restart,
+which will prevent any issues that a live list of URLs might cause.
+
**Example usage:**
```javascript
@@ -39,7 +47,8 @@ const requestList = new Apify.RequestList({
// Note that all URLs must start with http:// or https://
{ requestsFromUrl: 'http://www.example.com/my-url-list.txt', userData: { isFromUrl: true } },
],
- persistStateKey: 'my-crawling-state'
+ persistStateKey: 'my-state',
+ persistSourcesKey: 'my-sources'
});
// This call loads and parses the URLs from the remote file.
@@ -59,8 +68,9 @@ await requestList.reclaimRequest(request2);
* [RequestList](requestlist)
- * [`new RequestList(options)`](#new_RequestList_new)
+ * [`new exports.RequestList(options)`](#new_RequestList_new)
* [`.initialize()`](#RequestList+initialize) ⇒ <code>Promise</code>
+ * [`.persistState()`](#RequestList+persistState) ⇒ <code>Promise</code>
* [`.getState()`](#RequestList+getState) ⇒ <code>Object</code>
* [`.isEmpty()`](#RequestList+isEmpty) ⇒ <code>Promise&lt;Boolean&gt;</code>
* [`.isFinished()`](#RequestList+isFinished) ⇒ <code>Promise&lt;Boolean&gt;</code>
@@ -72,7 +82,7 @@ await requestList.reclaimRequest(request2);
<a name="new_RequestList_new"></a>
-## `new RequestList(options)`
+## `new exports.RequestList(options)`
<table>
<thead>
<tr>
@@ -105,15 +115,10 @@ await requestList.reclaimRequest(request2);
<td><code>[options.persistStateKey]</code></td><td><code>String</code></td><td></td>
</tr>
<tr>
-<td colspan="3"><p>Identifies the key in the default key-value store under which the <code>RequestList</code> persists its
- state. State represents a position of the last scraped request in the list. If this is set then <code>RequestList</code>
- persists this state in regular intervals and loads the state from there in case it is restarted due to an error or system reboot.</p>
-<p> <strong>IMPORTANT:</strong>
- The state represents only a pointer/index of a request in the list. The full contents of the list are not persisted.
- Therefore, the user is responsible for either persisting the list on her own or a consistent order of the requests
- in the list must be preserved. This is especially important when downloading a live list of URLs from a remote resource,
- since the change in the source URL list would change the resulting <code>RequestList</code> on error/restart and the state
- of crawling will be impossible to restore, resulting in an error.</p>
+<td colspan="3"><p>Identifies the keys in the default key-value store under which the <code>RequestList</code> persists its
+ initial sources and current state. State represents a position of the last scraped request in the list.
+ If this is set then <code>RequestList</code>persists all of its sources and the state in regular intervals
+ to key value store and loads the state from there in case it is restarted due to an error or system reboot.</p>
</td></tr><tr>
<td><code>[options.state]</code></td><td><code>Object</code></td><td></td>
</tr>
@@ -129,7 +134,7 @@ await requestList.reclaimRequest(request2);
},
}
</code></pre><p> Note that the preferred (and simpler) way to persist the state of crawling of the <code>RequestList</code>
- is to use the <code>persistStateKey</code> parameter instead.</p>
+ is to use the <code>stateKeyPrefix</code> parameter instead.</p>
</td></tr><tr>
<td><code>[options.keepDuplicateUrls]</code></td><td><code>Boolean</code></td><td><code>false</code></td>
</tr>
@@ -142,7 +147,7 @@ await requestList.reclaimRequest(request2);
<p> Setting <code>keepDuplicateUrls</code> to <code>true</code> will append an additional identifier to the <code>uniqueKey</code>
of each request that does not already include a <code>uniqueKey</code>. Therefore, duplicate
URLs will be kept in the list. It does not protect the user from having duplicates in user set
- <code>uniqueKey</code>s however. It is the user&#39;s responsibility to ensure uniqueness of their unique keys,
+ <code>uniqueKey</code>s however. It is the user&#39;s responsibility to ensure uniqueness of their unique keys
if they wish to keep more than just a single copy in the <code>RequestList</code>.</p>
</td></tr></tbody>
</table>
@@ -152,6 +157,15 @@ await requestList.reclaimRequest(request2);
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()` ⇒ <code>Promise</code>
+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
+or stop fetching its requests. For example after you pause or abort a crawl. Or just before
+a server migration.
+
<a name="RequestList+getState"></a>
## `requestList.getState()` ⇒ <code>Object</code>