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
Add cache to injectFile
Ondra Urban66ad5211f1c7
diff --git a/src/puppeteer_utils.js b/src/puppeteer_utils.jsindex 8f956c0cc..7670cf4db 100644--- a/src/puppeteer_utils.js+++ b/src/puppeteer_utils.js@@ -5,6 +5,7 @@ import _ from 'underscore';import log from 'apify-shared/log';import { checkParamOrThrow } from 'apify-client/build/utils';import { checkParamPrototypeOrThrow } from 'apify-shared/utilities';+import LruCache from 'apify-shared/lru_cache';import { RequestQueue, RequestQueueLocal } from './request_queue';import Request from './request';import { enqueueLinks } from './enqueue_links';@@ -13,6 +14,8 @@ const jqueryPath = require.resolve('jquery/dist/jquery.min');const underscorePath = require.resolve('underscore/underscore-min');const readFilePromised = util.promisify(fs.readFile);+const MAX_INJECT_FILE_CACHE_SIZE = 10;+/*** Hides certain Puppeteer fingerprints from the page, in order to help avoid detection of the crawler.* The function should be called on a newly-created page object before navigating to the target crawled page.@@ -54,11 +57,18 @@ const hideWebDriver = async (page) => {});};+/**+ * Cache contents of previously injected files to limit file system access.+ */+const injectedFilesCache = new LruCache({ maxLength: MAX_INJECT_FILE_CACHE_SIZE });+/*** Injects a JavaScript file into a Puppeteer page.* Unlike Puppeteer's `addScriptTag` function, this function works on pages* with arbitrary Cross-Origin Resource Sharing (CORS) policies.*+ * File contents are cached for up to 10 files to limit file system access.+ ** @param {Page} page* Puppeteer <a href="https://pptr.dev/#?product=Puppeteer&show=api-class-page" target="_blank"><code>Page</code></a> object.* @param {String} filePath File path@@ -75,7 +85,11 @@ const injectFile = async (page, filePath, options = {}) => {checkParamOrThrow(filePath, 'filePath', 'String');checkParamOrThrow(options, 'options', 'Object');- const contents = await readFilePromised(filePath, 'utf8');+ let contents = injectedFilesCache.get(filePath);+ if (!contents) {+ contents = await readFilePromised(filePath, 'utf8');+ injectedFilesCache.add(filePath, contents);+ }const evalP = page.evaluate(contents);return options.surviveNavigations? Promise.all([page.evaluateOnNewDocument(contents), evalP])