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.

feat: check enqueue link strategy post redirect (#2238)

Vlad Frangu3c5f9d605615
diff --git a/packages/basic-crawler/src/internals/basic-crawler.ts b/packages/basic-crawler/src/internals/basic-crawler.ts
index 62fc6947b..2677338ca 100644
--- a/packages/basic-crawler/src/internals/basic-crawler.ts
+++ b/packages/basic-crawler/src/internals/basic-crawler.ts
@@ -33,6 +33,7 @@ import {
CriticalError,
Dataset,
enqueueLinks,
+ EnqueueStrategy,
EventType,
KeyValueStore,
mergeCookies,
@@ -1575,6 +1576,52 @@ export class BasicCrawler<Context extends CrawlingContext = BasicCrawlingContext
return RequestQueue.open(null, { config: this.config });
}
+
+ protected requestMatchesEnqueueStrategy(request: Request) {
+ const { url, loadedUrl } = request;
+
+ // eslint-disable-next-line dot-notation -- private access
+ const strategy = request['enqueueStrategy'];
+
+ // No strategy set, so we assume it matches, or it was added outside of enqueueLinks
+ if (!strategy) {
+ return true;
+ }
+
+ // If we somehow don't have a loadedUrl, we can't check the strategy anyways, assume it matches
+ if (!loadedUrl) {
+ return true;
+ }
+
+ const baseUrl = new URL(url);
+ const loadedBaseUrl = new URL(loadedUrl);
+
+ switch (strategy) {
+ case EnqueueStrategy.SameHostname: {
+ return baseUrl.hostname === loadedBaseUrl.hostname;
+ }
+ case EnqueueStrategy.SameDomain: {
+ const baseUrlHostname = getDomain(baseUrl.hostname, { mixedInputs: false });
+
+ if (baseUrlHostname) {
+ const loadedBaseUrlHostname = getDomain(loadedBaseUrl.hostname, { mixedInputs: false });
+
+ return baseUrlHostname === loadedBaseUrlHostname;
+ }
+
+ // Can happen for IPs, we just check like same origin
+ return baseUrl.origin === loadedBaseUrl.origin;
+ }
+ case EnqueueStrategy.SameOrigin: {
+ // Same as hostname, but also checks protocol
+ return baseUrl.origin === loadedBaseUrl.origin;
+ }
+ case EnqueueStrategy.All:
+ default: {
+ return true;
+ }
+ }
+ }
}
export interface CreateContextOptions {
diff --git a/packages/browser-crawler/src/internals/browser-crawler.ts b/packages/browser-crawler/src/internals/browser-crawler.ts
index af7790630..f78ceaf7d 100644
--- a/packages/browser-crawler/src/internals/browser-crawler.ts
+++ b/packages/browser-crawler/src/internals/browser-crawler.ts
@@ -524,6 +524,15 @@ export abstract class BrowserCrawler<
}
}
+ if (!this.requestMatchesEnqueueStrategy(request)) {
+ this.log.debug(`Skipping request ${request.id} (${request.url}) because it does not match the enqueue strategy.`);
+
+ request.noRetry = true;
+ request.state = RequestState.SKIPPED;
+
+ return;
+ }
+
if (this.retryOnBlocked) {
if (await this.isRequestBlocked(crawlingContext)) {
throw new SessionError();
diff --git a/packages/core/src/enqueue_links/enqueue_links.ts b/packages/core/src/enqueue_links/enqueue_links.ts
index bd6e71060..7faffae6e 100644
--- a/packages/core/src/enqueue_links/enqueue_links.ts
+++ b/packages/core/src/enqueue_links/enqueue_links.ts
@@ -366,11 +366,11 @@ export async function enqueueLinks(options: SetRequired<EnqueueLinksOptions, 're
function createFilteredRequests() {
// No user provided patterns means we can skip an extra filtering step
if (urlPatternObjects.length === 0) {
- return createRequests(requestOptions, enqueueStrategyPatterns, urlExcludePatternObjects);
+ return createRequests(requestOptions, enqueueStrategyPatterns, urlExcludePatternObjects, options.strategy);
}
// Generate requests based on the user patterns first
- const generatedRequestsFromUserFilters = createRequests(requestOptions, urlPatternObjects, urlExcludePatternObjects);
+ const generatedRequestsFromUserFilters = createRequests(requestOptions, urlPatternObjects, urlExcludePatternObjects, options.strategy);
// ...then filter them by the enqueue links strategy (making this an AND check)
return filterRequestsByPatterns(generatedRequestsFromUserFilters, enqueueStrategyPatterns);
}
diff --git a/packages/core/src/enqueue_links/shared.ts b/packages/core/src/enqueue_links/shared.ts
index 7f6adf42f..d7c1694ab 100644
--- a/packages/core/src/enqueue_links/shared.ts
+++ b/packages/core/src/enqueue_links/shared.ts
@@ -134,10 +134,11 @@ export function createRequests(
requestOptions: (string | RequestOptions)[],
urlPatternObjects?: UrlPatternObject[],
excludePatternObjects: UrlPatternObject[] = [],
+ strategy?: EnqueueLinksOptions['strategy'],
): Request[] {
if (!urlPatternObjects || !urlPatternObjects.length) {
return requestOptions
- .map((opts) => new Request(typeof opts === 'string' ? { url: opts } : opts));
+ .map((opts) => new Request(typeof opts === 'string' ? { url: opts, enqueueStrategy: strategy } : { ...opts }));
}
const requests: Request[] = [];
@@ -167,8 +168,8 @@ export function createRequests(
(glob && minimatch(urlToMatch, glob, { nocase: true }))
) {
const request = typeof opts === 'string'
- ? { url: opts, ...requestRegExpOptions }
- : { ...opts, ...requestRegExpOptions };
+ ? { url: opts, ...requestRegExpOptions, enqueueStrategy: strategy }
+ : { ...opts, ...requestRegExpOptions, enqueueStrategy: strategy };
requests.push(new Request(request));
// Stop checking other patterns for this request option as it was already matched
@@ -210,10 +211,14 @@ export function filterRequestsByPatterns(requests: Request[], patterns?: UrlPatt
*/
export function createRequestOptions(
sources: (string | Record<string, unknown>)[],
- options: Pick<EnqueueLinksOptions, 'label' | 'userData' | 'baseUrl' | 'skipNavigation'> = {},
+ options: Pick<EnqueueLinksOptions, 'label' | 'userData' | 'baseUrl' | 'skipNavigation' | 'strategy'> = {},
): RequestOptions[] {
return sources
- .map((src) => (typeof src === 'string' ? { url: src } : src as unknown as RequestOptions))
+ .map(
+ (src) => (
+ typeof src === 'string' ? { url: src, enqueueStrategy: options.strategy } : { ...src, enqueueStrategy: options.strategy } as RequestOptions
+ ),
+ )
.filter(({ url }) => {
try {
return new URL(url, options.baseUrl).href;
diff --git a/packages/core/src/request.ts b/packages/core/src/request.ts
index 0a5a0cd56..ba7bfaeec 100644
--- a/packages/core/src/request.ts
+++ b/packages/core/src/request.ts
@@ -7,6 +7,7 @@ import type { Dictionary } from '@crawlee/types';
import type { BasePredicate } from 'ow';
import ow from 'ow';
+import type { EnqueueLinksOptions } from './enqueue_links/enqueue_links';
import { log as defaultLog } from './log';
import type { AllowedHttpMethods } from './typedefs';
import { keys } from './typedefs';
@@ -43,6 +44,7 @@ export enum RequestState {
DONE,
ERROR_HANDLER,
ERROR,
+ SKIPPED,
}
/**
@@ -171,6 +173,7 @@ export class Request<UserData extends Dictionary = Dictionary> {
keepUrlFragment = false,
useExtendedUniqueKey = false,
skipNavigation,
+ enqueueStrategy,
} = options as RequestOptions & {
loadedUrl?: string;
retryCount?: number;
@@ -245,6 +248,11 @@ export class Request<UserData extends Dictionary = Dictionary> {
if (skipNavigation != null) this.skipNavigation = skipNavigation;
if (maxRetries != null) this.maxRetries = maxRetries;
+
+ // If it's already set, don't override it (for instance when fetching from storage)
+ if (enqueueStrategy) {
+ this.enqueueStrategy ??= enqueueStrategy;
+ }
}
/** Tells the crawler processing this request to skip the navigation and process the request directly. */
@@ -313,6 +321,18 @@ export class Request<UserData extends Dictionary = Dictionary> {
}
}
+ private get enqueueStrategy(): EnqueueLinksOptions['strategy'] | undefined {
+ return this.userData.__crawlee?.enqueueStrategy;
+ }
+
+ private set enqueueStrategy(value: EnqueueLinksOptions['strategy']) {
+ if (!this.userData.__crawlee) {
+ (this.userData as Dictionary).__crawlee = { enqueueStrategy: value };
+ } else {
+ this.userData.__crawlee.enqueueStrategy = value;
+ }
+ }
+
/**
* Stores information about an error that occurred during processing of this request.
*
@@ -483,6 +503,8 @@ export interface RequestOptions<UserData extends Dictionary = Dictionary> {
/** @internal */
lockExpiresAt?: Date;
+ /** @internal */
+ enqueueStrategy?: EnqueueLinksOptions['strategy'];
}
export interface PushErrorMessageOptions {
diff --git a/packages/core/test/enqueue_links/add-enqueue-strategy-to-requests.ts b/packages/core/test/enqueue_links/add-enqueue-strategy-to-requests.ts
new file mode 100644
index 000000000..4f6f89a83
--- /dev/null
+++ b/packages/core/test/enqueue_links/add-enqueue-strategy-to-requests.ts
@@ -0,0 +1,63 @@
+import log from '@apify/log';
+import { load } from 'cheerio';
+import type { Source } from 'crawlee';
+import { EnqueueStrategy, Configuration, cheerioCrawlerEnqueueLinks, RequestQueue } from 'crawlee';
+
+const apifyClient = Configuration.getStorageClient();
+
+const HTML = `
+<html>
+ <head>
+ <title>Example</title>
+ </head>
+ <body>
+ <ul>
+ <li>
+ <a class="first" href="https://menicka.cz/redirect.php?w=akce&id=f1ab8ae200bddaa17fd50150943d1e06">
+ I'm sorry, Dave. I'm afraid I can't do that.
+ </a>
+ </li>
+ </ul>
+ </body>
+</html>
+`;
+
+function createRequestQueueMock() {
+ const enqueued: Source[] = [];
+ const requestQueue = new RequestQueue({ id: 'xxx', client: apifyClient });
+
+ // @ts-expect-error Override method for testing
+ requestQueue.addRequests = async function (requests) {
+ enqueued.push(...requests);
+ return { processedRequests: requests, unprocessedRequests: [] as never[] };
+ };
+
+ return { enqueued, requestQueue };
+}
+
+describe('enqueueLinks() - it should store the enqueue strategy in requests', () => {
+ let ll: number;
+ beforeAll(() => {
+ ll = log.getLevel();
+ log.setLevel(log.LEVELS.ERROR);
+ });
+
+ afterAll(() => {
+ log.setLevel(ll);
+ });
+
+ const $ = load(HTML);
+
+ test('it should store the enqueue strategy in requests', async () => {
+ const { enqueued, requestQueue } = createRequestQueueMock();
+
+ await cheerioCrawlerEnqueueLinks({
+ options: { selector: 'a', strategy: EnqueueStrategy.SameHostname },
+ $,
+ requestQueue,
+ originalRequestUrl: 'https://menicka.cz',
+ });
+
+ expect(enqueued[0].userData!.__crawlee.enqueueStrategy).toEqual(EnqueueStrategy.SameHostname);
+ });
+});
diff --git a/packages/http-crawler/src/internals/http-crawler.ts b/packages/http-crawler/src/internals/http-crawler.ts
index fa2fefc8f..15076503b 100644
--- a/packages/http-crawler/src/internals/http-crawler.ts
+++ b/packages/http-crawler/src/internals/http-crawler.ts
@@ -457,6 +457,7 @@ export class HttpCrawler<Context extends InternalHttpCrawlingContext<any, any, H
const sessionId = session ? session.id : undefined;
crawlingContext.proxyInfo = await this.proxyConfiguration.newProxyInfo(sessionId);
}
+
if (!request.skipNavigation) {
await this._handleNavigation(crawlingContext);
tryCancel();
@@ -479,6 +480,15 @@ export class HttpCrawler<Context extends InternalHttpCrawlingContext<any, any, H
request.loadedUrl = response.url;
+ if (!this.requestMatchesEnqueueStrategy(request)) {
+ this.log.debug(`Skipping request ${request.id} (${request.url}) because it does not match the enqueue strategy.`);
+
+ request.noRetry = true;
+ request.state = RequestState.SKIPPED;
+
+ return;
+ }
+
Object.assign(crawlingContext, parsed);
Object.defineProperty(crawlingContext, 'json', {
diff --git a/test/core/crawlers/browser_crawler.test.ts b/test/core/crawlers/browser_crawler.test.ts
index 1f1f63692..c72c0d7be 100644
--- a/test/core/crawlers/browser_crawler.test.ts
+++ b/test/core/crawlers/browser_crawler.test.ts
@@ -11,6 +11,7 @@ import type {
} from '@crawlee/puppeteer';
import {
AutoscaledPool,
+ EnqueueStrategy,
ProxyConfiguration,
Request,
RequestList,
@@ -106,6 +107,7 @@ describe('BrowserCrawler', () => {
expect(request.userData.title).toBe('Example Domain');
});
});
+
test('should teardown browser pool', async () => {
const requestList = await RequestList.open({
sources: [
@@ -1020,4 +1022,25 @@ describe('BrowserCrawler', () => {
await browserCrawler.run();
});
});
+
+ test("enqueueLinks() should skip links that don't match the strategy post redirect", async () => {
+ const succeeded: string[] = [];
+
+ const crawler = new BrowserCrawlerTest({
+ browserPoolOptions: {
+ browserPlugins: [puppeteerPlugin],
+ },
+ maxConcurrency: 1,
+ maxRequestRetries: 0,
+ requestHandler: async ({ page, enqueueLinks }) => {
+ succeeded.push(await page.title());
+ await enqueueLinks({ strategy: EnqueueStrategy.SameOrigin });
+ },
+ });
+
+ await crawler.run([`${serverAddress}/special/redirect`]);
+
+ expect(succeeded).toHaveLength(1);
+ expect(succeeded[0]).toEqual('Redirecting outside');
+ });
});
diff --git a/test/core/crawlers/cheerio_crawler.test.ts b/test/core/crawlers/cheerio_crawler.test.ts
index 909d3ae77..aa0dc169e 100644
--- a/test/core/crawlers/cheerio_crawler.test.ts
+++ b/test/core/crawlers/cheerio_crawler.test.ts
@@ -1,7 +1,7 @@
import type { IncomingHttpHeaders, Server } from 'http';
import { Readable } from 'stream';
-import log, { Log } from '@apify/log';
+import log, { Log, LogLevel } from '@apify/log';
import type {
CheerioRequestHandler,
CheerioCrawlingContext,
@@ -13,6 +13,7 @@ import {
CheerioCrawler,
CrawlerExtension,
createCheerioRouter,
+ EnqueueStrategy,
mergeCookies,
ProxyConfiguration,
Request,
@@ -21,7 +22,6 @@ import {
} from '@crawlee/cheerio';
import { sleep } from '@crawlee/utils';
import type { Dictionary } from '@crawlee/utils';
-// @ts-expect-error This throws a compilation error due to got-scraping being ESM only but we only import types, so its alllll gooooood\
import type { OptionsInit } from 'got-scraping';
import iconv from 'iconv-lite';
import { runExampleComServer, responseSamples } from 'test/shared/_helper';
@@ -31,6 +31,30 @@ let server: Server;
let port: number;
let serverAddress = 'http://localhost:';
+async function getRequestListForMock(mockData: Dictionary, pathName = 'special/mock') {
+ const sources: Source[] = [1, 2, 3, 4].map((num) => {
+ return {
+ url: `${serverAddress}/${pathName}?a=${num}`,
+ payload: JSON.stringify(mockData),
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ };
+ });
+ const requestList = await RequestList.open(null, sources);
+ return requestList;
+}
+
+async function getRequestListForMirror() {
+ const sources = [
+ { url: `${serverAddress}/special/mirror?a=12` },
+ { url: `${serverAddress}/special/mirror?a=23` },
+ { url: `${serverAddress}/special/mirror?a=33` },
+ { url: `${serverAddress}/special/mirror?a=43` },
+ ];
+ const requestList = await RequestList.open(null, sources);
+ return requestList;
+}
+
beforeAll(async () => {
[server, port] = await runExampleComServer();
serverAddress += port;
@@ -1318,28 +1342,22 @@ describe('CheerioCrawler', () => {
expect(failed).toHaveLength(0);
});
-});
-async function getRequestListForMock(mockData: Dictionary, pathName = 'special/mock') {
- const sources: Source[] = [1, 2, 3, 4].map((num) => {
- return {
- url: `${serverAddress}/${pathName}?a=${num}`,
- payload: JSON.stringify(mockData),
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- };
- });
- const requestList = await RequestList.open(null, sources);
- return requestList;
-}
+ test("enqueueLinks() should skip links that don't match the strategy post redirect", async () => {
+ const succeeded: string[] = [];
-async function getRequestListForMirror() {
- const sources = [
- { url: `${serverAddress}/special/mirror?a=12` },
- { url: `${serverAddress}/special/mirror?a=23` },
- { url: `${serverAddress}/special/mirror?a=33` },
- { url: `${serverAddress}/special/mirror?a=43` },
- ];
- const requestList = await RequestList.open(null, sources);
- return requestList;
-}
+ const crawler = new CheerioCrawler({
+ maxConcurrency: 1,
+ maxRequestRetries: 0,
+ requestHandler: async ({ $, enqueueLinks }) => {
+ succeeded.push($('title').text());
+ await enqueueLinks({ strategy: EnqueueStrategy.SameOrigin });
+ },
+ });
+
+ await crawler.run([`${serverAddress}/special/redirect`]);
+
+ expect(succeeded).toHaveLength(1);
+ expect(succeeded[0]).toEqual('Redirecting outside');
+ });
+});
diff --git a/test/shared/_helper.ts b/test/shared/_helper.ts
index b4553814f..9a2bfc1b8 100644
--- a/test/shared/_helper.ts
+++ b/test/shared/_helper.ts
@@ -103,6 +103,15 @@ body {
console.log('Hello world!');
`,
},
+ htmlWithOutsideRedirect: `
+<html>
+ <head>
+ <title>Redirecting outside</title>
+ </head>
+ <body>
+ <a href="/special/redirect-outside">click me</a>
+ </body>
+</html>`,
cloudflareBlocking: `
<!DOCTYPE html>
<head>
@@ -247,6 +256,14 @@ export async function runExampleComServer(): Promise<[Server, number]> {
res.type('html').send(responseSamples.resources);
});
+ special.get('/redirect', (_req, res) => {
+ res.type('html').send(responseSamples.htmlWithOutsideRedirect);
+ });
+
+ special.get('/redirect-outside', (req, res) => {
+ res.redirect('https://example.com');
+ });
+
special.get('/cloudflareBlocking', async (_req, res) => {
res
.type('html')