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.

Add keepDuplicateUrls option

Ondra Urbanfc59f988d4f8
diff --git a/src/request_list.js b/src/request_list.js
index 364585314..6f4ba2202 100644
--- a/src/request_list.js
+++ b/src/request_list.js
@@ -1,3 +1,4 @@
+import crypto from 'crypto';
import { checkParamOrThrow } from 'apify-client/build/utils';
import log from 'apify-shared/log';
import _ from 'underscore';
@@ -59,7 +60,11 @@ const ensureUniqueKeyValid = (uniqueKey) => {
* ```
*
* @param {Object} options
- * @param {Array} options.sources Function that processes a request. It must return a promise.
+ * @param {Array} options.sources An array of sources for the `RequestList`. Its contents can either be just plain objects,
+ * defining at least a 'url' property, or instances of the `Request` class. See the `Request`
+ * class for available properties. Additionally a `requestsFromUrl` property may be used instead
+ * of `url`, which will instruct the `RequestList` to download the sources from the given URL.
+ * URLs will be parsed from the received response.
* ```javascript
* [
* // One URL
@@ -84,16 +89,27 @@ const ensureUniqueKeyValid = (uniqueKey) => {
* }
* ```
* Note that the preferred (and simpler) way to persist the state of crawling of the `RequestList` is to use the `persistStateKey` parameter instead.
+ *
+ * @param {Boolean} [options.keepDuplicateUrls=false] By default, `RequestList` will deduplicate the provided URLs. Default deduplication is based
+ * on the `uniqueKey` property of passed sources. If not present, it is generated by normalizing
+ * the URL. If present, it is kept intact. In any case, only one request per `uniqueKey` is added
+ * to the `RequestList` resulting in removing of duplicate URLs / unique keys.
+ * Setting `keepDuplicateUrls` to true will generate a random unique identifier for each request
+ * that does not already include a `uniqueKey` to be used as the unique key. Therefore, duplicate
+ * URLs will be kept in the list. It does not protect the user from having duplicates in user set
+ * `uniqueKey`s however. It is the user's responsibility to ensure uniqueness of their unique keys,
+ * if they wish to keep more than just a single copy in the `RequestList`.
*/
export default class RequestList {
constructor(opts = {}) {
checkParamOrThrow(opts, 'options', 'Object');
- const { sources, persistStateKey, state } = opts;
+ const { sources, persistStateKey, state, keepDuplicateUrls = false } = opts;
checkParamOrThrow(sources, 'options.sources', 'Array');
checkParamOrThrow(state, 'options.state', 'Maybe Object');
checkParamOrThrow(persistStateKey, 'options.persistStateKey', 'Maybe String');
+ checkParamOrThrow(keepDuplicateUrls, 'options.keepDuplicateUrls', 'Maybe Boolean');
// We will initialize everything from this state in this.initialize();
this.initialStatePromise = persistStateKey && !state
@@ -123,6 +139,9 @@ export default class RequestList {
this.persistStateKey = persistStateKey;
this.isStatePersisted = true;
+ // If this option is set then all requests will get a pre-generated unique ID and duplicate URLs will be kept in the list.
+ this.keepDuplicateUrls = keepDuplicateUrls;
+
this.isLoading = false;
this.isInitialized = false;
this.sources = sources;
@@ -394,11 +413,16 @@ export default class RequestList {
/**
* Adds given request.
- * If opts parameter is plain object not instance of an Requests then creates it.
+ * If opts parameter is a plain object and not an instance of a Request then creates it.
*
* @ignore
*/
_addRequest(opts) {
+ // Generate random uniqueKey if duplicates are to be kept
+ if (this.keepDuplicateUrls && !opts.uniqueKey) {
+ opts.uniqueKey = crypto.randomBytes(20).toString('base64').replace(/[+/=]/g, '');
+ }
+
const request = opts instanceof Request
? opts
: new Request(opts);
@@ -407,9 +431,11 @@ export default class RequestList {
ensureUniqueKeyValid(uniqueKey);
// Skip requests with duplicate uniqueKey
- if (this.uniqueKeyToIndex[uniqueKey] === undefined) {
+ if (!this.uniqueKeyToIndex.hasOwnProperty(uniqueKey)) { // eslint-disable-line no-prototype-builtins
this.uniqueKeyToIndex[uniqueKey] = this.requests.length;
this.requests.push(request);
+ } else if (this.keepDuplicateUrls) {
+ log.warning(`RequestList: Duplicate uniqueKey: ${uniqueKey} found while the keepDuplicateUrls option was set. Check your sources' unique keys.`); // eslint-disable-line max-len
}
}
diff --git a/test/request_list.js b/test/request_list.js
index 45c104ba0..7eb9c7ece 100644
--- a/test/request_list.js
+++ b/test/request_list.js
@@ -514,4 +514,38 @@ describe('Apify.RequestList', () => {
expect(requestList.length()).to.be.eql(4);
});
+
+ it('should correctly keep duplicate URLs while keepDuplicateUrls is set', async () => {
+ const sources = [
+ { url: 'https://www.example.com' },
+ { url: 'https://www.example.com' },
+ { url: 'https://www.example.com' },
+ { url: 'https://www.ex2mple.com' },
+ ];
+
+ let requestList = new Apify.RequestList({
+ sources,
+ keepDuplicateUrls: true,
+ });
+
+ await requestList.initialize();
+ expect(requestList.length()).to.be.eql(4);
+
+ const log = sinon.stub(console, 'log');
+
+ requestList = new Apify.RequestList({
+ sources: sources.concat([
+ { url: 'https://www.example.com', uniqueKey: '123' },
+ { url: 'https://www.example.com', uniqueKey: '123' },
+ { url: 'https://www.example.com', uniqueKey: '456' },
+ { url: 'https://www.ex2mple.com', uniqueKey: '456' },
+ ]),
+ keepDuplicateUrls: true,
+ });
+
+ await requestList.initialize();
+ expect(requestList.length()).to.be.eql(6);
+ expect(log.called).to.be.eql(true);
+ expect(log.getCall(0).args[0]).to.include('Check your sources\' unique keys.');
+ });
});