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.
TypeScript apifyautomationcrawlercrawlingheadlessheadless-chromejavascriptnodejsnpmplaywrightpuppeteerscraperscrapingtypescriptweb-crawlerweb-crawlingweb-scraping
Tests pass
Ondra Urbanb114474a5f37
diff --git a/src/autoscaled_pool.js b/src/autoscaled_pool.jsindex 6cd2918e1..97e7f7f62 100644--- a/src/autoscaled_pool.js+++ b/src/autoscaled_pool.js@@ -220,6 +220,13 @@ export default class AutoscaledPool {});}+ /**+ * Stops the auto-scaled pool, discarding all currently running tasks.+ */+ stop() {+ if (this.resolve) this.resolve();+ }+/*** Gets called every AUTOSCALE_INTERVAL_MILLIS and saves number of free bytes in this.freeBytesSnapshots.*diff --git a/src/basic_crawler.js b/src/basic_crawler.jsindex b24f44063..219eed55a 100644--- a/src/basic_crawler.js+++ b/src/basic_crawler.js@@ -139,7 +139,7 @@ export default class BasicCrawler {const isMaxPagesExceeded = () => maxRequestsPerCrawl && maxRequestsPerCrawl <= this.handledRequestsCount;- this.autoscaledPool = new AutoscaledPool({+ this.autoscaledPoolOptions = {maxMemoryMbytes,maxConcurrency,minConcurrency,@@ -162,7 +162,8 @@ export default class BasicCrawler {: this._defaultIsFinishedFunction();},ignoreMainProcess,- });+ };+ this.autoscaledPool = new AutoscaledPool(this.autoscaledPoolOptions);}/**@@ -171,14 +172,17 @@ export default class BasicCrawler {* @return {Promise}*/run() {+ if (this.isStopped) this.autoscaledPool = new AutoscaledPool(this.autoscaledPoolOptions);this.isStopped = false;return this.autoscaledPool.run();}+/**- * Stops the crawler by preventing crawls of additional pages. Pages already running are not terminated.+ * Stops the crawler by preventing crawls of additional pages. Pages already running are NOT terminated.*/stop() {this.isStopped = true;+ this.autoscaledPool.stop();}/**@@ -241,32 +245,36 @@ export default class BasicCrawler {.then(() => source.markRequestHandled(request)).catch((error) => {if (request.ignoreErrors) {- log.exception(error, 'BasicCrawler: handleRequestFunction failed, request.ignoreErrors=true so marking the request as handled', { // eslint-disable-line max-len- url: request.url,- retryCount: request.retryCount,- });-+ if (!this.isStopped) {+ log.exception(error, 'BasicCrawler: handleRequestFunction failed, request.ignoreErrors=true so marking the request as handled', { // eslint-disable-line max-len+ url: request.url,+ retryCount: request.retryCount,+ });+ }return source.markRequestHandled(request);}- request.pushErrorMessage(error);+ if (!this.isStopped) request.pushErrorMessage(error);// Retry request.if (request.retryCount < this.maxRequestRetries) {- request.retryCount++;- log.exception(error, 'BasicCrawler: handleRequestFunction failed, reclaiming failed request back to the list or queue', {- url: request.url,- retryCount: request.retryCount,- });+ if (!this.isStopped) {+ request.retryCount++;+ log.exception(error, 'BasicCrawler: handleRequestFunction failed, reclaiming failed request back to the list or queue', { // eslint-disable-line max-len+ url: request.url,+ retryCount: request.retryCount,+ });+ }willBeRetried = true;-return source.reclaimRequest(request);}- log.exception(error, 'BasicCrawler: handleRequestFunction failed, marking failed request as handled', {- url: request.url,- retryCount: request.retryCount,- });+ if (!this.isStopped) {+ log.exception(error, 'BasicCrawler: handleRequestFunction failed, marking failed request as handled', {+ url: request.url,+ retryCount: request.retryCount,+ });+ }// Mark as failed.return source@@ -313,6 +321,8 @@ export default class BasicCrawler {return Promise.all(promises)- .then(results => _.all(results));+ .then((results) => {+ return _.all(results);+ });}}diff --git a/src/puppeteer_crawler.js b/src/puppeteer_crawler.jsindex 79ff83d3e..3b9ccc35f 100644--- a/src/puppeteer_crawler.js+++ b/src/puppeteer_crawler.js@@ -170,14 +170,16 @@ export default class PuppeteerCrawler {this.gotoFunction = gotoFunction;this.pageOpsTimeoutMillis = pageOpsTimeoutMillis;- this.puppeteerPool = new PuppeteerPool({+ this.puppeteerPoolOptions = {maxOpenPagesPerInstance,retireInstanceAfterRequestCount,instanceKillerIntervalMillis,killInstanceAfterMillis,launchPuppeteerFunction,launchPuppeteerOptions,- });+ };++ this.puppeteerPool = new PuppeteerPool(this.puppeteerPoolOptions);this.basicCrawler = new BasicCrawler({// Basic crawler options.@@ -204,22 +206,38 @@ export default class PuppeteerCrawler {* @return {Promise}*/run() {+ if (this.isStopped) this.puppeteerPool = new PuppeteerPool(this.puppeteerPoolOptions);+ this.stopPromise = new Promise((resolve, reject) => {+ this.stopPromiseResolve = reject;+ });+ this.isStopped = false;return this.basicCrawler.run().finally(() => this.puppeteerPool.destroy());}+ /**+ * Stops the crawler by preventing crawls of additional pages. Pages already running are terminated.+ */+ stop() {+ this.isStopped = true;+ this.stopPromiseResolve();+ this.basicCrawler.stop();+ return this.puppeteerPool.destroy();+ }+/*** Wrapper around handlePageFunction that opens and closes pages etc.** @ignore*/_handleRequestFunction({ request }) {+ if (this.isStopped) return Promise.reject(new Error('PuppeteerCrawler is stopped.')); // Pool will be destroyed.let page;const handlePagePromise = this.puppeteerPool.newPage().then((newPage) => { page = newPage; })- .then(() => this.gotoFunction({ page, request, puppeteerPool: this.puppeteerPool }))+ .then(() => this._gotoFunction({ page, request, puppeteerPool: this.puppeteerPool })).then((response) => {const promise = this.handlePageFunction({page,@@ -233,13 +251,20 @@ export default class PuppeteerCrawler {return promise;});- return handlePagePromise+ const finalPromise = handlePagePromise.timeout(this.pageOpsTimeoutMillis, 'PuppeteerCrawler: handlePageFunction timed out.').finally(() => {+ if (this.isStopped) return; // Pool will clean up itself.return Promise.try(() => page.close()).timeout(PAGE_CLOSE_TIMEOUT_MILLIS, 'Operation timed out.').catch(err => log.debug('PuppeteerCrawler: Page.close() failed.', { reason: err ? err.message : err }));});+ return Promise.race([finalPromise, this.stopPromise]);+ }++ _gotoFunction(...args) {+ if (this.isStopped) return Promise.reject(new Error('PuppeteerCrawler is stopped.'));+ return this.gotoFunction(...args);}}diff --git a/src/puppeteer_pool.js b/src/puppeteer_pool.jsindex 97650cbdd..6e9b1f155 100644--- a/src/puppeteer_pool.js+++ b/src/puppeteer_pool.js@@ -110,6 +110,7 @@ export default class PuppeteerPool {checkParamOrThrow(launchPuppeteerOptions, 'opts.launchPuppeteerOptions', 'Maybe Object');// Config.+ this.isDestroyed = false;this.maxOpenPagesPerInstance = maxOpenPagesPerInstance;this.retireInstanceAfterRequestCount = retireInstanceAfterRequestCount;this.killInstanceAfterMillis = killInstanceAfterMillis;@@ -290,6 +291,7 @@ export default class PuppeteerPool {return page;}).catch((err) => {+ if (this.isDestroyed) return;log.exception(err, 'PuppeteerPool: browser.newPage() failed', { id: instance.id });this._retireInstance(instance);@@ -302,6 +304,7 @@ export default class PuppeteerPool {* Closes all the browsers.*/destroy() {+ this.isDestroyed = true;clearInterval(this.instanceKillerInterval);process.removeListener('SIGINT', this.sigintListener);diff --git a/test/basic_crawler.js b/test/basic_crawler.jsindex e121dfc66..2f4d38ec2 100644--- a/test/basic_crawler.js+++ b/test/basic_crawler.js@@ -38,6 +38,43 @@ describe('BasicCrawler', () => {expect(await requestList.isEmpty()).to.be.eql(true);});+ it('should run, stop and then finish', async () => {+ const sources = _.range(500).map(index => ({ url: `https://example.com/${index}` }));++ let basicCrawler;+ const processed = [];+ const requestList = new Apify.RequestList({ sources });+ const handleRequestFunction = async ({ request }) => {+ if (request.url.endsWith('200')) {+ basicCrawler.stop();+ }+ await delayPromise(10);+ processed.push(_.pick(request, 'url'));+ };++ basicCrawler = new Apify.BasicCrawler({+ requestList,+ minConcurrency: 25,+ maxConcurrency: 25,+ handleRequestFunction,+ });++ await requestList.initialize();++ // The crawler will stop after 200 requests+ await basicCrawler.run();++ expect(processed.length).to.be.above(175);+ expect(processed.length).to.be.below(201);+ expect(await requestList.isFinished()).to.be.eql(false);+ expect(await requestList.isEmpty()).to.be.eql(false);++ await basicCrawler.run();+ expect(processed).to.be.eql(sources);+ expect(await requestList.isFinished()).to.be.eql(true);+ expect(await requestList.isEmpty()).to.be.eql(true);+ });+it('should retry failed requests', async () => {const sources = [{ url: 'http://example.com/1' },diff --git a/test/puppeteer_crawler.js b/test/puppeteer_crawler.jsindex cd0c43f91..57b5dc45f 100644--- a/test/puppeteer_crawler.js+++ b/test/puppeteer_crawler.js@@ -1,6 +1,7 @@import chai, { expect } from 'chai';import chaiAsPromised from 'chai-as-promised';import 'babel-polyfill';+import _ from 'underscore';import { ENV_VARS } from '../build/constants';import * as Apify from '../build/index';@@ -58,6 +59,64 @@ describe('PuppeteerCrawler', () => {});});+ it('should stop and resume', async () => {+ const comparator = (a, b) => {+ a = Number(/q=(\d+)$/.exec(a.url)[1]);+ b = Number(/q=(\d+)$/.exec(b.url)[1]);+ return a - b;+ };+ const sources = _.range(30).map(index => ({ url: `https://example.com/?q=${index}` }));+ let puppeteerCrawler;+ let isStopped = false;+ const processed = [];+ const failed = [];+ const requestList = new Apify.RequestList({ sources });+ const handlePageFunction = async ({ page, request, response }) => {+ if (request.url.endsWith('15') && !isStopped) {+ await puppeteerCrawler.stop();+ isStopped = true;+ }+ await page.waitFor('title');+ expect(await response.status()).to.be.eql(200);+ request.userData.title = await page.title();+ processed.push(request);+ };++ puppeteerCrawler = new Apify.PuppeteerCrawler({+ requestList,+ minConcurrency: 3,+ maxConcurrency: 3,+ handlePageFunction,+ handleFailedRequestFunction: ({ request }) => failed.push(request),+ });++ await requestList.initialize();+ await puppeteerCrawler.run();++ expect(processed.length).to.be.above(12);+ expect(processed.length).to.be.below(16);+ expect(failed).to.have.lengthOf(0);++ processed.sort(comparator);++ processed.forEach((request, id) => {+ expect(request.url).to.be.eql(sources[id].url);+ expect(request.userData.title).to.be.eql('Example Domain');+ });++ await puppeteerCrawler.run();++ expect(processed).to.have.lengthOf(30);+ expect(failed).to.have.lengthOf(0);++ processed.sort(comparator);++ processed.forEach((request, id) => {+ expect(request.url).to.be.eql(sources[id].url);+ expect(request.userData.title).to.be.eql('Example Domain');+ });+ });+it('should ignore errors in Page.close()', async () => {for (let i = 0; i < 2; i++) {const requestList = new Apify.RequestList({