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.

feat: allow running single crawler instance multiple times (#1844)

Martin Adámek9e6eb1e32f58
diff --git a/packages/basic-crawler/src/internals/basic-crawler.ts b/packages/basic-crawler/src/internals/basic-crawler.ts
index 1bd53a1b8..a0b17e9a3 100644
--- a/packages/basic-crawler/src/internals/basic-crawler.ts
+++ b/packages/basic-crawler/src/internals/basic-crawler.ts
@@ -369,6 +369,8 @@ export class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContext
*/
readonly router: RouterHandler<Context> = Router.create<Context>();
+ running?: boolean;
+
protected log: Log;
protected requestHandler!: RequestHandler<Context>;
protected errorHandler?: ErrorHandler<Context>;
@@ -651,7 +653,26 @@ export class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContext
* @param [requests] The requests to add
* @param [options] Options for the request queue
*/
- async run(requests?: (string | Request | RequestOptions)[], options?: CrawlerAddRequestsOptions): Promise<FinalStatistics> {
+ async run(requests?: (string | Request | RequestOptions)[], options?: CrawlerRunOptions): Promise<FinalStatistics> {
+ if (this.running) {
+ throw new Error('This crawler instance is already running, you can add more requests to it via `crawler.addRequests()`.');
+ }
+
+ const purgeRequestQueue = options?.purgeRequestQueue ?? true;
+
+ // When executing the run method for the second time explicitly (the first time `this.running` is `undefined`),
+ // we need to purge the default RQ to allow processing the same requests again - this is important so users can
+ // pass in failed requests back to the `crawler.run()`, otherwise they would be considered as handled and
+ // ignored - as a failed requests is still handled.
+ if (this.running === false && this.requestQueue?.name === 'default' && purgeRequestQueue) {
+ await this.requestQueue.drop();
+ this.requestQueue = await RequestQueue.open();
+ }
+
+ this.running = true;
+ this.stats.reset();
+ await this.stats.resetStore();
+
await purgeDefaultStorages();
if (requests) {
@@ -721,6 +742,8 @@ export class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContext
periodicLogger.stop();
// eslint-disable-next-line max-len
await this.setStatusMessage(`Finished! Total ${this.stats.state.requestsFinished + this.stats.state.requestsFailed} requests: ${this.stats.state.requestsFinished} succeeded, ${this.stats.state.requestsFailed} failed.`, { isStatusMessageTerminal: true });
+ this.running = false;
+
return stats;
}
@@ -1308,11 +1331,20 @@ export interface CreateContextOptions {
export interface CrawlerAddRequestsOptions extends RequestQueueOperationOptions {
/**
* Whether to wait for all the provided requests to be added, instead of waiting just for the initial batch of up to 1000.
- @default false
+ * @default false
*/
waitForAllRequestsToBeAdded?: boolean;
}
+export interface CrawlerRunOptions extends CrawlerAddRequestsOptions {
+ /**
+ * Whether to purge the RequestQueue before running the crawler again. Defaults to true, so it is possible to reprocess failed requests.
+ * When disabled, only new requests will be considered. Note that even a failed request is considered as handled.
+ * @default true
+ */
+ purgeRequestQueue?: boolean;
+}
+
export interface CrawlerAddRequestsResult {
addedRequests: ProcessedRequest[];
/**
diff --git a/packages/core/src/crawlers/statistics.ts b/packages/core/src/crawlers/statistics.ts
index 44ada6d59..362c67a02 100644
--- a/packages/core/src/crawlers/statistics.ts
+++ b/packages/core/src/crawlers/statistics.ts
@@ -148,6 +148,14 @@ export class Statistics {
this._teardown();
}
+ async resetStore() {
+ if (!this.keyValueStore) {
+ return;
+ }
+
+ await this.keyValueStore.setValue(this.persistStateKey, null);
+ }
+
/**
* Increments the status code counter.
*/
diff --git a/test/core/crawlers/basic_crawler.test.ts b/test/core/crawlers/basic_crawler.test.ts
index e621bb596..d5097c9d3 100644
--- a/test/core/crawlers/basic_crawler.test.ts
+++ b/test/core/crawlers/basic_crawler.test.ts
@@ -108,6 +108,29 @@ describe('BasicCrawler', () => {
expect(await requestList.isEmpty()).toBe(true);
});
+ test('should allow using run method multiple times', async () => {
+ const sources = [...Array(100).keys()].map((index) => `https://example.com/${index}`);
+ const sourcesCopy = JSON.parse(JSON.stringify(sources));
+
+ const processed: { url: string }[] = [];
+ const requestHandler: RequestHandler = async ({ request }) => {
+ await sleep(10);
+ processed.push({ url: request.url });
+ };
+
+ const basicCrawler = new BasicCrawler({
+ minConcurrency: 25,
+ maxConcurrency: 25,
+ requestHandler,
+ });
+
+ await basicCrawler.run(sources);
+ await basicCrawler.run(sources);
+ await basicCrawler.run(sources);
+
+ expect(processed).toHaveLength(sourcesCopy.length * 3);
+ });
+
test('should correctly combine shorthand and full length options', async () => {
const shorthandOptions = {
minConcurrency: 123,
diff --git a/test/e2e/playwright-multi-run/actor/.actor/actor.json b/test/e2e/playwright-multi-run/actor/.actor/actor.json
new file mode 100644
index 000000000..46cf4e07f
--- /dev/null
+++ b/test/e2e/playwright-multi-run/actor/.actor/actor.json
@@ -0,0 +1,7 @@
+{
+ "actorSpecification": 1,
+ "name": "test-playwright-multi-run",
+ "version": "0.0",
+ "buildTag": "latest",
+ "env": null
+}
diff --git a/test/e2e/playwright-multi-run/actor/.gitignore b/test/e2e/playwright-multi-run/actor/.gitignore
new file mode 100644
index 000000000..ced7cbfc5
--- /dev/null
+++ b/test/e2e/playwright-multi-run/actor/.gitignore
@@ -0,0 +1,7 @@
+.idea
+.DS_Store
+node_modules
+package-lock.json
+apify_storage
+crawlee_storage
+storage
diff --git a/test/e2e/playwright-multi-run/actor/Dockerfile b/test/e2e/playwright-multi-run/actor/Dockerfile
new file mode 100644
index 000000000..58d737169
--- /dev/null
+++ b/test/e2e/playwright-multi-run/actor/Dockerfile
@@ -0,0 +1,23 @@
+FROM node:16 AS builder
+
+COPY /packages ./packages
+COPY /package*.json ./
+RUN npm --quiet set progress=false \
+ && npm install --only=prod --no-optional \
+ && npm update
+
+FROM apify/actor-node-playwright-chrome:16-beta
+
+RUN rm -r node_modules
+COPY --from=builder /node_modules ./node_modules
+COPY --from=builder /packages ./packages
+COPY --from=builder /package*.json ./
+COPY /.actor ./.actor
+COPY /main.js ./
+
+RUN echo "Installed NPM packages:" \
+ && (npm list --only=prod --no-optional --all || true) \
+ && echo "Node.js version:" \
+ && node --version \
+ && echo "NPM version:" \
+ && npm --version
diff --git a/test/e2e/playwright-multi-run/actor/main.js b/test/e2e/playwright-multi-run/actor/main.js
new file mode 100644
index 000000000..6dcb2fe69
--- /dev/null
+++ b/test/e2e/playwright-multi-run/actor/main.js
@@ -0,0 +1,27 @@
+import { Actor } from 'apify';
+import { Dataset, PlaywrightCrawler } from '@crawlee/playwright';
+import { ApifyStorageLocal } from '@apify/storage-local';
+
+if (process.env.STORAGE_IMPLEMENTATION === 'LOCAL') {
+ await Actor.init({ storage: new ApifyStorageLocal() });
+} else {
+ await Actor.init();
+}
+
+const crawler = new PlaywrightCrawler({
+ maxRequestsPerCrawl: 10,
+ async requestHandler({ page, enqueueLinks, request }) {
+ const { url } = request;
+ const pageTitle = await page.title();
+ await Dataset.pushData({ url, pageTitle });
+ await enqueueLinks({
+ globs: ['**/3.0/examples/*'],
+ });
+ },
+});
+
+await crawler.run(['https://crawlee.dev/docs/3.0/examples/']);
+await crawler.run(['https://crawlee.dev/docs/3.0/examples/']);
+await crawler.run(['https://crawlee.dev/docs/3.0/examples/']);
+
+await Actor.exit({ exit: Actor.isAtHome() });
diff --git a/test/e2e/playwright-multi-run/actor/package.json b/test/e2e/playwright-multi-run/actor/package.json
new file mode 100644
index 000000000..e6c47e153
--- /dev/null
+++ b/test/e2e/playwright-multi-run/actor/package.json
@@ -0,0 +1,29 @@
+{
+ "name": "test-playwright-multi-run",
+ "version": "0.0.1",
+ "description": "Playwright Test - Multiple run calls to the same crawler",
+ "dependencies": {
+ "apify": "next",
+ "@apify/storage-local": "^2.1.0",
+ "@crawlee/basic": "file:./packages/basic-crawler",
+ "@crawlee/browser": "file:./packages/browser-crawler",
+ "@crawlee/browser-pool": "file:./packages/browser-pool",
+ "@crawlee/core": "file:./packages/core",
+ "@crawlee/memory-storage": "file:./packages/memory-storage",
+ "@crawlee/playwright": "file:./packages/playwright-crawler",
+ "@crawlee/types": "file:./packages/types",
+ "@crawlee/utils": "file:./packages/utils",
+ "playwright": "*"
+ },
+ "overrides": {
+ "apify": {
+ "@crawlee/core": "file:./packages/core",
+ "@crawlee/utils": "file:./packages/utils"
+ }
+ },
+ "scripts": {
+ "start": "node main.js"
+ },
+ "type": "module",
+ "license": "ISC"
+}
diff --git a/test/e2e/playwright-multi-run/test.mjs b/test/e2e/playwright-multi-run/test.mjs
new file mode 100644
index 000000000..9bd2759ec
--- /dev/null
+++ b/test/e2e/playwright-multi-run/test.mjs
@@ -0,0 +1,10 @@
+import { initialize, getActorTestDir, runActor, expect, validateDataset } from '../tools.mjs';
+
+const testActorDirname = getActorTestDir(import.meta.url);
+await initialize(testActorDirname);
+
+const { datasetItems } = await runActor(testActorDirname, 16384);
+
+// we cant assert number of requests as the stats KVS is being wiped on each `run` call, unlike the dataset
+await expect(datasetItems.length > 30, 'Number of dataset items');
+await expect(validateDataset(datasetItems, ['url', 'pageTitle']), 'Dataset items validation');