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.

Implement comments

Ondra Urbande601dd8c2a3
diff --git a/src/puppeteer_pool.js b/src/puppeteer_pool.js
index 66b5ac274..1d6a1fe30 100644
--- a/src/puppeteer_pool.js
+++ b/src/puppeteer_pool.js
@@ -15,7 +15,7 @@ const PROCESS_KILL_TIMEOUT_MILLIS = 5000;
const PAGE_CLOSE_KILL_TIMEOUT_MILLIS = 1000;
const DEFAULT_OPTIONS = {
- reusePages: true,
+ reusePages: false,
// Don't make these too large, otherwise Puppeteer might start crashing weirdly,
// and the default settings should just work
maxOpenPagesPerInstance: 50,
@@ -103,7 +103,7 @@ class PuppeteerInstance {
* ```
* @param {Object} [options] All `PuppeteerPool` parameters are passed
* via an options object with the following keys:
- * @param {boolean} [options.reusePages=true]
+ * @param {boolean} [options.reusePages=false]
* 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.
@@ -216,11 +216,15 @@ class PuppeteerPool {
this.browserCounter = 0;
this.activeInstances = {};
this.retiredInstances = {};
+ this.lastUsedProxyUrlIndex = 0;
+ this.instanceKillerInterval = setInterval(() => this._killRetiredInstances(), instanceKillerIntervalMillis);
this.idlePages = [];
+ // WeakSet/Map items do not prevent garbage collection,
+ // and thus no management of the collections is needed.
+ // They will automatically empty themselves once there
+ // are no references to the stored pages.
this.closedPages = new WeakSet();
this.pagesToInstancesMap = new WeakMap();
- this.lastUsedProxyUrlIndex = 0;
- this.instanceKillerInterval = setInterval(() => this._killRetiredInstances(), instanceKillerIntervalMillis);
// ensure termination on SIGINT
this.sigintListener = () => this._killAllInstances();
@@ -405,7 +409,7 @@ class PuppeteerPool {
* @param {PuppeteerInstance} instance
* @ignore
*/
- _updateInstance(instance) {
+ _incrementPageCount(instance) {
instance.lastPageOpenedAt = Date.now();
instance.totalPages++;
if (instance.totalPages >= this.retireInstanceAfterRequestCount) this._retireInstance(instance);
@@ -433,7 +437,7 @@ class PuppeteerPool {
const instance = this.pagesToInstancesMap.get(idlePage);
const instanceIsActive = !!this.activeInstances[instance.id];
if (pageIsNotClosed && instanceIsActive) {
- this._updateInstance(instance);
+ this._incrementPageCount(instance);
return idlePage;
}
}
@@ -455,7 +459,7 @@ class PuppeteerPool {
.find(inst => inst.activePages < this.maxOpenPagesPerInstance);
if (!instance) instance = this._launchInstance();
- this._updateInstance(instance);
+ this._incrementPageCount(instance);
instance.activePages++;
try {
@@ -483,11 +487,14 @@ class PuppeteerPool {
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 }));
+ .catch((err) => {
+ const instance = this.pagesToInstancesMap.get(page);
+ log.debug('PuppeteerPool: Page.close() failed', { errorMessage: err.message, id: instance.id });
+ });
};
page.once('error', (error) => {
- log.exception(error, 'PuppeteerPool: page crashed');
+ log.exception(error, 'PuppeteerPool: page crashed.');
page.close();
});
return page;
diff --git a/test/puppeteer_pool.js b/test/puppeteer_pool.js
index 73949a5bc..6abf1d2d5 100644
--- a/test/puppeteer_pool.js
+++ b/test/puppeteer_pool.js
@@ -319,8 +319,10 @@ describe('PuppeteerPool', () => {
});
describe('reuse of browser tabs', () => {
- it('should work by default', async () => {
- const pool = new Apify.PuppeteerPool();
+ it('should work', async () => {
+ const pool = new Apify.PuppeteerPool({
+ reusePages: true,
+ });
const firstPage = await pool.newPage();
const secondPage = await pool.newPage();
await pool.recyclePage(firstPage);
@@ -351,24 +353,28 @@ describe('PuppeteerPool', () => {
it('should not open new browsers when idle pages are available', async () => {
const pool = new Apify.PuppeteerPool({
maxOpenPagesPerInstance: 1,
+ reusePages: true,
});
- let page = await pool.newPage();
- await pool.recyclePage(page);
+ const pageOne = await pool.newPage();
+ await pool.recyclePage(pageOne);
expect(Object.keys(pool.activeInstances).length).to.be.eql(1);
- page = await pool.newPage();
- await pool.recyclePage(page);
+ const pageTwo = await pool.newPage();
+ expect(pageOne === pageTwo).to.be.eql(true);
+ await pool.recyclePage(pageTwo);
expect(Object.keys(pool.activeInstances).length).to.be.eql(1);
- page = await pool.newPage();
+ const pageThree = await pool.newPage();
+ expect(pageTwo === pageThree).to.be.eql(true);
expect(Object.keys(pool.activeInstances).length).to.be.eql(1);
- const pageTwo = await pool.newPage();
+ const pageFour = await pool.newPage();
+ expect(pageFour === pageThree).to.be.eql(false);
expect(Object.keys(pool.activeInstances).length).to.be.eql(2);
- await pool.recyclePage(page);
- await pool.recyclePage(pageTwo);
+ await pool.recyclePage(pageThree);
+ await pool.recyclePage(pageFour);
await pool.newPage();
await pool.newPage();
expect(Object.keys(pool.activeInstances).length).to.be.eql(2);
@@ -379,6 +385,7 @@ describe('PuppeteerPool', () => {
it('should count towards retireInstanceAfterRequestCount option', async () => {
const pool = new Apify.PuppeteerPool({
retireInstanceAfterRequestCount: 2,
+ reusePages: true,
});
const len = obj => Object.keys(obj).length;
@@ -414,7 +421,7 @@ describe('PuppeteerPool', () => {
});
it('should skip closed pages', async () => {
- const pool = new Apify.PuppeteerPool();
+ const pool = new Apify.PuppeteerPool({ reusePages: true });
const firstPage = await pool.newPage();
const secondPage = await pool.newPage();