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
Allowing to override is finished function of BasicCrawler and PuppeteerCrawler (#55)
Marek Trunkátfb36c2a3138f
diff --git a/src/autoscaled_pool.js b/src/autoscaled_pool.jsindex a5d8a0221..1e063f00f 100644--- a/src/autoscaled_pool.js+++ b/src/autoscaled_pool.js@@ -311,7 +311,8 @@ export default class AutoscaledPool {** @ignore*/- _maybeRunTask() {+ _maybeRunTask(recursion = 0) {+ if (recursion >= this.concurrency) return;if (this.runningCount >= this.concurrency) return;if (this.queryingIsTaskReady) return;@@ -346,7 +347,7 @@ export default class AutoscaledPool {if (!isPromise(taskPromise)) throw new Error('User provided runTaskFunction must return a Promise.');this.runningCount++;- this._maybeRunTask();+ this._maybeRunTask(recursion + 1);return taskPromise.then(() => {diff --git a/src/basic_crawler.js b/src/basic_crawler.jsindex 65fc44c65..3d0388a10 100644--- a/src/basic_crawler.js+++ b/src/basic_crawler.js@@ -54,6 +54,11 @@ const DEFAULT_OPTIONS = {* @param {Number} [options.maxConcurrency=1000] Maximum number of request to process in parallel (see `AutoscaledPool`).* @param {Number} [options.minConcurrency=1] Minimum number of request to process in parallel (see `AutoscaledPool`).* @param {Number} [options.minFreeMemoryRatio=0.2] Minimum ratio of free memory kept in the system.+ * @param {Function} [opts.isFinishedFunction] By default BasicCrawler finishes when all the requests have been processed.+ * You can override this behaviour by providing custom `isFinishedFunction`.+ * This function that is called every time there are no requests being processed.+ * If it resolves to `true` then the crawler's run finishes.+ * See `isFinishedFunction` parameter of `AutoscaledPool`.*/export default class BasicCrawler {constructor(opts) {@@ -69,13 +74,15 @@ export default class BasicCrawler {maxConcurrency,minConcurrency,minFreeMemoryRatio,+ isFinishedFunction,} = _.defaults(opts, DEFAULT_OPTIONS);+ checkParamPrototypeOrThrow(requestList, 'opts.requestList', RequestList, 'Apify.RequestList', true);+ checkParamPrototypeOrThrow(requestQueue, 'opts.requestQueue', RequestQueue, 'Apify.RequestQueue', true);checkParamOrThrow(handleRequestFunction, 'opts.handleRequestFunction', 'Function');checkParamOrThrow(handleFailedRequestFunction, 'opts.handleFailedRequestFunction', 'Function');checkParamOrThrow(maxRequestRetries, 'opts.maxRequestRetries', 'Number');- checkParamPrototypeOrThrow(requestList, 'opts.requestList', RequestList, 'Apify.RequestList', true);- checkParamPrototypeOrThrow(requestQueue, 'opts.requestQueue', RequestQueue, 'Apify.RequestQueue', true);+ checkParamOrThrow(isFinishedFunction, 'opts.isFinishedFunction', 'Maybe Function');if (!requestList && !requestQueue) {throw new Error('At least one of the parameters "opts.requestList" and "opts.requestQueue" must be provided!');@@ -93,8 +100,12 @@ export default class BasicCrawler {minConcurrency,minFreeMemoryRatio,runTaskFunction: () => this._runTaskFunction(),- isFinishedFunction: () => this._isFinishedFunction(),isTaskReadyFunction: () => this._isTaskReadyFunction(),+ isFinishedFunction: () => (+ isFinishedFunction+ ? isFinishedFunction()+ : this._defaultIsFinishedFunction()+ ),});}@@ -206,7 +217,7 @@ export default class BasicCrawler {** @ignore*/- _isFinishedFunction() {+ _defaultIsFinishedFunction() {const promises = [];if (this.requestList) promises.push(this.requestList.isFinished());diff --git a/src/puppeteer_crawler.js b/src/puppeteer_crawler.jsindex 76054f86c..2b762f07c 100644--- a/src/puppeteer_crawler.js+++ b/src/puppeteer_crawler.js@@ -66,7 +66,13 @@ const DEFAULT_OPTIONS = {* @param {Number} [options.maxMemoryMbytes] Maximum memory available for crawling. See `maxMemoryMbytes` parameter of `AutoscaledPool`.* @param {Number} [options.maxConcurrency=1000] Maximum concurrency of request processing. See `maxConcurrency` parameter of `AutoscaledPool`.* @param {Number} [options.minConcurrency=1] Minimum concurrency of requests processing. See `minConcurrency` parameter of `AutoscaledPool`.- * @param {Number} [options.minFreeMemoryRatio=0.2] Minimum ratio of free memory kept in the system.+ * @param {Number} [options.minFreeMemoryRatio=0.2] Minimum ratio of free memory kept in the system. See `minFreeMemoryRatio` parameter of+ * `AutoscaledPool`.+ * @param {Function} [opts.isFinishedFunction] By default PuppeteerCrawler finishes when all the requests have been processed.+ * You can override this behaviour by providing custom `isFinishedFunction`.+ * This function that is called every time there are no requests being processed.+ * If it resolves to `true` then the crawler's run finishes.+ * See `isFinishedFunction` parameter of `AutoscaledPool`.* @param {Number} [options.maxOpenPagesPerInstance=100] Maximum number of opened tabs per browser. If this limit is reached then a new* browser instance is started. See `maxOpenPagesPerInstance` parameter of `PuppeteerPool`.* @param {Number} [options.abortInstanceAfterRequestCount=150] Maximum number of requests that can be processed by a single browser instance.@@ -98,6 +104,7 @@ export default class PuppeteerCrawler {maxConcurrency,minConcurrency,minFreeMemoryRatio,+ isFinishedFunction,// Basic crawler optionsrequestList,@@ -152,6 +159,7 @@ export default class PuppeteerCrawler {maxConcurrency,minConcurrency,minFreeMemoryRatio,+ isFinishedFunction,});}diff --git a/test/basic_crawler.js b/test/basic_crawler.jsindex 2c5f23990..874af77c4 100644--- a/test/basic_crawler.js+++ b/test/basic_crawler.js@@ -278,4 +278,42 @@ describe('BasicCrawler', () => {expect(await crawler._isTaskReadyFunction()).to.be.eql(false);});++ it('should be possible to override isFinishedFunction of underlying AutoscaledPool', async () => {+ const requestQueue = new RequestQueue('xxx');+ const processed = [];+ const queue = [];+ let isFinished = false;++ const basicCrawler = new Apify.BasicCrawler({+ requestQueue,+ minConcurrency: 1,+ maxConcurrency: 1,+ handleRequestFunction: async ({ request }) => {+ await delayPromise(10);+ processed.push(request);+ },+ isFinishedFunction: () => {+ return Promise.resolve(isFinished);+ },+ });++ const request0 = new Apify.Request({ url: 'http://example.com/0' });+ const request1 = new Apify.Request({ url: 'http://example.com/1' });++ const mock = sinon.mock(requestQueue);+ mock.expects('markRequestHandled').once().withArgs(request0).returns(Promise.resolve());+ mock.expects('markRequestHandled').once().withArgs(request1).returns(Promise.resolve());+ mock.expects('isFinished').never();+ requestQueue.fetchNextRequest = () => Promise.resolve(queue.pop());+ requestQueue.isEmpty = () => Promise.resolve(!queue.length);++ setTimeout(() => queue.push(request0), 2000);+ setTimeout(() => queue.push(request1), 2500);+ setTimeout(() => { isFinished = true; }, 3500);++ await basicCrawler.run();++ expect(processed).to.be.eql([request0, request1]);+ });});