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
Implement, add tests
Ondra Urbande5b9152ab09
diff --git a/src/puppeteer_crawler.js b/src/puppeteer_crawler.jsindex 6075b7c0f..28a5138d9 100644--- a/src/puppeteer_crawler.js+++ b/src/puppeteer_crawler.js@@ -313,7 +313,7 @@ class PuppeteerCrawler {return await Promise.race([pageOperationsPromise, this.rejectOnAbortPromise]);} finally {try {- await Promise.race([page.close(), createTimeoutPromise(PAGE_CLOSE_TIMEOUT_MILLIS, 'Operation timed out.')]);+ await Promise.race([this.puppeteerPool.recyclePage(page), createTimeoutPromise(PAGE_CLOSE_TIMEOUT_MILLIS, 'Operation timed out.')]);} catch (err) {log.debug('PuppeteerCrawler: Page.close() failed.', { reason: err && err.message });}diff --git a/src/puppeteer_pool.js b/src/puppeteer_pool.jsindex 1c4532d15..66b5ac274 100644--- a/src/puppeteer_pool.js+++ b/src/puppeteer_pool.js@@ -15,6 +15,7 @@ const PROCESS_KILL_TIMEOUT_MILLIS = 5000;const PAGE_CLOSE_KILL_TIMEOUT_MILLIS = 1000;const DEFAULT_OPTIONS = {+ reusePages: true,// Don't make these too large, otherwise Puppeteer might start crashing weirdly,// and the default settings should just workmaxOpenPagesPerInstance: 50,@@ -102,6 +103,10 @@ class PuppeteerInstance {* ```* @param {Object} [options] All `PuppeteerPool` parameters are passed* via an options object with the following keys:+ * @param {boolean} [options.reusePages=true]+ * Individual browser tabs will be reused after their task is complete instead+ * of closing them and spawning a new tab. This saves CPU resources.+ * Try disabling this feature if you encounter any weird behavior in your crawlers.* @param {Number} [options.maxOpenPagesPerInstance=50]* Maximum number of open pages (i.e. tabs) per browser. When this limit is reached, new pages are loaded in a new browser instance.* @param {Number} [options.retireInstanceAfterRequestCount=100]@@ -140,6 +145,7 @@ class PuppeteerPool {}const {+ reusePages,maxOpenPagesPerInstance,retireInstanceAfterRequestCount,launchPuppeteerFunction,@@ -154,6 +160,7 @@ class PuppeteerPool {// Re-enable once the issues upstream are fixed.const recycleDiskCache = false;+ checkParamOrThrow(reusePages, 'options.reusePages', 'Boolean');checkParamOrThrow(maxOpenPagesPerInstance, 'options.maxOpenPagesPerInstance', 'Number');checkParamOrThrow(retireInstanceAfterRequestCount, 'options.retireInstanceAfterRequestCount', 'Number');checkParamOrThrow(launchPuppeteerFunction, 'options.launchPuppeteerFunction', 'Function');@@ -175,6 +182,7 @@ class PuppeteerPool {}// Config.+ this.reusePages = reusePages;this.maxOpenPagesPerInstance = maxOpenPagesPerInstance;this.retireInstanceAfterRequestCount = retireInstanceAfterRequestCount;this.killInstanceAfterMillis = killInstanceAfterMillis;@@ -208,6 +216,9 @@ class PuppeteerPool {this.browserCounter = 0;this.activeInstances = {};this.retiredInstances = {};+ this.idlePages = [];+ this.closedPages = new WeakSet();+ this.pagesToInstancesMap = new WeakMap();this.lastUsedProxyUrlIndex = 0;this.instanceKillerInterval = setInterval(() => this._killRetiredInstances(), instanceKillerIntervalMillis);@@ -388,44 +399,70 @@ class PuppeteerPool {});}+ /**+ * Updates the instance metadata when a new page is opened.+ *+ * @param {PuppeteerInstance} instance+ * @ignore+ */+ _updateInstance(instance) {+ instance.lastPageOpenedAt = Date.now();+ instance.totalPages++;+ if (instance.totalPages >= this.retireInstanceAfterRequestCount) this._retireInstance(instance);+ }++ /**+ * 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.+ *+ * To spawn a new browser tab for each page, set the `reusePages` constructor option to false.+ *+ * @return {Promise<Page>}+ */+ async newPage() {+ let idlePage;+ // We don't need to check whether options.reusePages is true,+ // because if it's false, the array will be empty and the loop will never start.+ while (idlePage = this.idlePages.shift()) { // eslint-disable-line no-cond-assign+ // Since pages can close for various reasons that we have no control over,+ // we need to make sure that we're only using live pages, so we go+ // through the queue until we get a page that's live, which means+ // that it's not closed and its browser is not retired.+ const pageIsNotClosed = !this.closedPages.has(idlePage);+ const instance = this.pagesToInstancesMap.get(idlePage);+ const instanceIsActive = !!this.activeInstances[instance.id];+ if (pageIsNotClosed && instanceIsActive) {+ this._updateInstance(instance);+ return idlePage;+ }+ }+ // If there are no live pages to be reused, we spawn a new tab.+ return this._openNewTab();+ }+/*** Opens new tab in one of the browsers in the pool and returns a `Promise`* that resolves to an instance of a Puppeteer* <a href="https://pptr.dev/#?product=Puppeteer&show=api-class-page" target="_blank"><code>Page</code></a>.** @return {Promise<Page>}+ * @ignore*/- async newPage() {- let instance;-- _.mapObject(this.activeInstances, (inst) => {- if (inst.activePages >= this.maxOpenPagesPerInstance) return;-- instance = inst;- });+ async _openNewTab() {+ let instance = Object+ .values(this.activeInstances)+ .find(inst => inst.activePages < this.maxOpenPagesPerInstance);if (!instance) instance = this._launchInstance();-- instance.lastPageOpenedAt = Date.now();- instance.totalPages++;+ this._updateInstance(instance);instance.activePages++;- if (instance.totalPages >= this.retireInstanceAfterRequestCount) this._retireInstance(instance);-try {const browser = await instance.browserPromise;const page = await browser.newPage();-- page.once('error', (error) => {- log.exception(error, 'PuppeteerPool: page crashed');- // Swallow errors from Page.close()- page.close()- .catch(err => log.debug('PuppeteerPool: Page.close() failed', { errorMessage: err.message, id: instance.id }));- });-- // TODO: log console messages page.on('console', message => log.debug(`Chrome console: ${message.text}`));-- return page;+ this.pagesToInstancesMap.set(page, instance);+ return this._decoratePage(page);} catch (err) {log.exception(err, 'PuppeteerPool: browser.newPage() failed', { id: instance.id });this._retireInstance(instance);@@ -435,6 +472,27 @@ class PuppeteerPool {}}+ /**+ * Adds the necessary boilerplate to allow page reuse and also+ * captures page.close() errors to prevent meaningless log clutter.+ * @param page+ * @ignore+ */+ _decoratePage(page) {+ const originalPageClose = page.close;+ page.close = async (...args) => {+ this.closedPages.add(page);+ return originalPageClose.apply(page, args)+ .catch(err => log.debug('PuppeteerPool: Page.close() failed', { errorMessage: err.message, id: instance.id }));+ };++ page.once('error', (error) => {+ log.exception(error, 'PuppeteerPool: page crashed');+ page.close();+ });+ return page;+ }+/*** Closes all open browsers.* @return {Promise}@@ -510,6 +568,24 @@ class PuppeteerPool {if (instance) return this._retireInstance(instance);log.debug('PuppeteerPool: browser is retired already');}++ /**+ * Recycles the page, which means that it will be enqueued for future reuse+ * instead of spawning a new tab. This is done automatically unless the `reusePages`+ * option of the `PuppeteerPool` constructor is set to false. You can also use this+ * function manually to tell the pool that you no longer need this specific page+ * and it can be reused in the future.+ *+ * Using this function without setting the `reusePages` option to false causes+ * this function to trigger a page.close().+ *+ * @param {Page} page+ * @return {Promise}+ */+ async recyclePage(page) {+ if (this.reusePages) this.idlePages.push(page);+ else await page.close();+ }}export default PuppeteerPool;diff --git a/test/puppeteer_pool.js b/test/puppeteer_pool.jsindex 1c5ececaf..73949a5bc 100644--- a/test/puppeteer_pool.js+++ b/test/puppeteer_pool.js@@ -89,7 +89,7 @@ describe('PuppeteerPool', () => {expect(pool.retiredInstances[0].activePages).to.be.eql(3);expect(pool.retiredInstances[0].totalPages).to.be.eql(5);- // Kill the remaning 3 pages from the 1st browser to see that it gets closed.+ // Kill the remaining 3 pages from the 1st browser to see that it gets closed.await (await browsers[2]).close();await (await browsers[6]).close();@@ -318,6 +318,138 @@ describe('PuppeteerPool', () => {expect(fs.existsSync(dir3)).to.be.eql(false);});+ describe('reuse of browser tabs', () => {+ it('should work by default', async () => {+ const pool = new Apify.PuppeteerPool();+ const firstPage = await pool.newPage();+ const secondPage = await pool.newPage();+ await pool.recyclePage(firstPage);+ const recycledFirstPage = await pool.newPage();+ const thirdPage = await pool.newPage();+ await pool.recyclePage(thirdPage);+ await pool.recyclePage(secondPage);+ const recycledThirdPage = await pool.newPage();+ const recycledSecondPage = await pool.newPage();++ expect(recycledFirstPage === firstPage).to.be.eql(true);+ expect(recycledSecondPage === secondPage).to.be.eql(true);+ expect(recycledThirdPage === thirdPage).to.be.eql(true);++ expect(firstPage === secondPage).to.be.eql(false);+ expect(firstPage === thirdPage).to.be.eql(false);+ expect(firstPage === recycledSecondPage).to.be.eql(false);+ expect(firstPage === recycledThirdPage).to.be.eql(false);+ expect(secondPage === thirdPage).to.be.eql(false);+ expect(secondPage === recycledFirstPage).to.be.eql(false);+ expect(secondPage === recycledThirdPage).to.be.eql(false);+ expect(thirdPage === recycledFirstPage).to.be.eql(false);+ expect(thirdPage === recycledSecondPage).to.be.eql(false);++ await pool.destroy();+ });++ it('should not open new browsers when idle pages are available', async () => {+ const pool = new Apify.PuppeteerPool({+ maxOpenPagesPerInstance: 1,+ });++ let page = await pool.newPage();+ await pool.recyclePage(page);+ expect(Object.keys(pool.activeInstances).length).to.be.eql(1);++ page = await pool.newPage();+ await pool.recyclePage(page);+ expect(Object.keys(pool.activeInstances).length).to.be.eql(1);++ page = await pool.newPage();+ expect(Object.keys(pool.activeInstances).length).to.be.eql(1);++ const pageTwo = await pool.newPage();+ expect(Object.keys(pool.activeInstances).length).to.be.eql(2);++ await pool.recyclePage(page);+ await pool.recyclePage(pageTwo);+ await pool.newPage();+ await pool.newPage();+ expect(Object.keys(pool.activeInstances).length).to.be.eql(2);++ await pool.destroy();+ });++ it('should count towards retireInstanceAfterRequestCount option', async () => {+ const pool = new Apify.PuppeteerPool({+ retireInstanceAfterRequestCount: 2,+ });++ const len = obj => Object.keys(obj).length;++ let page = await pool.newPage();+ await pool.recyclePage(page);+ expect(len(pool.activeInstances)).to.be.eql(1);+ expect(len(pool.retiredInstances)).to.be.eql(0);++ page = await pool.newPage();+ await pool.recyclePage(page);+ expect(len(pool.activeInstances)).to.be.eql(0);+ expect(len(pool.retiredInstances)).to.be.eql(1);++ page = await pool.newPage();+ expect(len(pool.activeInstances)).to.be.eql(1);+ expect(len(pool.retiredInstances)).to.be.eql(1);++ const pageTwo = await pool.newPage();+ expect(len(pool.activeInstances)).to.be.eql(0);+ expect(len(pool.retiredInstances)).to.be.eql(2);++ await pool.recyclePage(page);+ await pool.recyclePage(pageTwo);+ expect(len(pool.activeInstances)).to.be.eql(0);+ await pool.newPage();+ expect(len(pool.activeInstances)).to.be.eql(1);+ await pool.newPage();+ expect(len(pool.retiredInstances)).to.be.eql(3);+ expect(len(pool.activeInstances)).to.be.eql(0);++ await pool.destroy();+ });++ it('should skip closed pages', async () => {+ const pool = new Apify.PuppeteerPool();++ const firstPage = await pool.newPage();+ const secondPage = await pool.newPage();+ await pool.recyclePage(firstPage);+ await pool.recyclePage(secondPage);+ await firstPage.close();+ const recycledSecondPage = await pool.newPage();+ const thirdPage = await pool.newPage();+ await thirdPage.close();+ const fourthPage = await pool.newPage();+ await secondPage.close();+ const fifthPage = await pool.newPage();+ await pool.recyclePage(recycledSecondPage);+ await pool.recyclePage(thirdPage);+ await pool.recyclePage(fourthPage);+ await pool.recyclePage(fifthPage);+ await fourthPage.close();+ const recycledFifthPage = await pool.newPage();++ expect(recycledSecondPage === secondPage).to.be.eql(true);+ expect(recycledFifthPage === fifthPage).to.be.eql(true);++ const all = [firstPage, secondPage, thirdPage, fourthPage, fifthPage, recycledSecondPage, recycledFifthPage];+ const matches = page => all.filter(x => page === x).length;++ expect(matches(firstPage)).to.be.eql(1);+ expect(matches(secondPage)).to.be.eql(2);+ expect(matches(thirdPage)).to.be.eql(1);+ expect(matches(fourthPage)).to.be.eql(1);+ expect(matches(fifthPage)).to.be.eql(2);++ await pool.destroy();+ });+ });+describe('the proxyUrls parameter', () => {it('supports rotation of custom proxies', async () => {const optionsLog = [];