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
fix: use one enqueue strategy implementation for enqueueLinks, sitemaps and robots.txt (#4345)
SwastikTripathib98c57355531
diff --git a/docs/upgrading/upgrading-v4/upgrading-v4.md b/docs/upgrading/upgrading-v4/upgrading-v4.mdindex 576c846ae..1866a0b89 100644--- a/docs/upgrading/upgrading-v4/upgrading-v4.md+++ b/docs/upgrading/upgrading-v4/upgrading-v4.md@@ -1037,6 +1037,10 @@ await enqueueLinks({});```+### Enqueue strategies ignore the port, except `same-origin`++In `enqueueLinks`, `same-hostname` and `same-domain` now compare hostnames only, so `http://example.com:8080/a` matches a base URL of `https://example.com/`. In v3, `enqueueLinks` required the port to match. `same-origin` still requires the same scheme, hostname and port. Hosts without a registrable domain (IP addresses, `localhost`) are matched by `same-domain` like `same-hostname`. Sitemap and robots.txt filtering and the post-redirect strategy check follow the same rules.+### `transformRequestFunction` precedence in `enqueueLinks`The `transformRequestFunction` callback in `enqueueLinks` now runs **after** URL pattern filtering (`include`, `exclude`) instead of before. This means it has the highest priority and can overwrite any request options set by the global `label` / `userData` options.diff --git a/packages/basic-crawler/src/internals/basic-crawler.ts b/packages/basic-crawler/src/internals/basic-crawler.tsindex 84827eaed..ce98e5d0d 100644--- a/packages/basic-crawler/src/internals/basic-crawler.ts+++ b/packages/basic-crawler/src/internals/basic-crawler.ts@@ -50,9 +50,16 @@ import type {SetStatusMessageOptions,StorageBackend,} from '@crawlee/types';-import { isAsyncIterable, isIterable, parseArgument, ROTATE_PROXY_ERRORS, schemas } from '@crawlee/utils/internal';+import {+ filterUrl,+ isAsyncIterable,+ isIterable,+ matchesEnqueueStrategy,+ parseArgument,+ ROTATE_PROXY_ERRORS,+ schemas,+} from '@crawlee/utils/internal';import { RobotsTxtFile } from '@crawlee/utils';-import { getDomain } from 'tldts';import type { ReadonlyDeep } from 'type-fest';import { z } from 'zod';@@ -86,7 +93,6 @@ import { Statistics } from './crawlers/statistics.js';import type { EnqueueUrlsOptions, SkippedRequestCallback } from './enqueue-links/index.js';import {applyRequestTransform,- buildEnqueueStrategyPatterns,constructUrlPatternObjects,createRequestOptions,createSkippedRequestArgs,@@ -2094,7 +2100,7 @@ export class BasicCrawler<const urlPatternObjects = options.include?.length ? constructUrlPatternObjects(options.include) : [];// The strategy always applies, even when `include` patterns are provided - the two are AND-ed together// (a URL must match an `include` pattern *and* satisfy the strategy). This mirrors crawlee-python.- const enqueueStrategyPatterns = options.baseUrl ? buildEnqueueStrategyPatterns(options.baseUrl, strategy) : [];+ const strategyBaseUrl = options.baseUrl ? new URL(options.baseUrl) : undefined;const isAllowedBasedOnRobotsTxtFile = this.#isAllowedBasedOnRobotsTxtFile.bind(this);const maxCrawlDepth = this.#maxCrawlDepth;@@ -2175,13 +2181,13 @@ export class BasicCrawler<onSkippedByFilter,);// ...then filter by the enqueue strategy (making this an AND check)- filtered = filterRequestOptionsByPatterns(- filtered,- enqueueStrategyPatterns.length > 0 ? enqueueStrategyPatterns : undefined,- [],- strategy,- onSkippedByFilter,- );+ if (strategyBaseUrl) {+ filtered = filtered.filter((opts) => {+ const { allowed } = filterUrl(opts.url, strategyBaseUrl, strategy);+ if (!allowed) onSkippedByFilter(opts);+ return allowed;+ });+ }if (filtered.length === 0) {continue;@@ -3103,34 +3109,7 @@ export class BasicCrawler<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 baseUrl.protocol === 'http:' || baseUrl.protocol === 'https:';- }- }+ return matchesEnqueueStrategy(strategy, new URL(loadedUrl), new URL(url));}}diff --git a/packages/basic-crawler/src/internals/enqueue-links/enqueue-links.ts b/packages/basic-crawler/src/internals/enqueue-links/enqueue-links.tsindex 1b146ba64..caddf7755 100644--- a/packages/basic-crawler/src/internals/enqueue-links/enqueue-links.ts+++ b/packages/basic-crawler/src/internals/enqueue-links/enqueue-links.ts@@ -4,7 +4,7 @@ import { getDomain } from 'tldts';import type { EnqueueStrategyOption, RequestQueueOperationOptions } from '@crawlee/core';-import type { RequestTransform, SkippedRequestCallback, UrlPatternInput, UrlPatternObject } from './shared.js';+import type { RequestTransform, SkippedRequestCallback, UrlPatternInput } from './shared.js';/*** Options shared by the `extractLinks()` context helper across crawler types.@@ -201,49 +201,3 @@ export interface ResolveBaseUrl {originalRequestUrl: string;finalRequestUrl?: string;}--/**- * @internal- * Builds the glob patterns a URL must match to satisfy the given enqueue `strategy`, anchored at `baseUrl`.- */-export function buildEnqueueStrategyPatterns(baseUrl: string, strategy: EnqueueStrategyOption): UrlPatternObject[] {- const url = new URL(baseUrl);-- switch (strategy) {- case EnqueueStrategy.SameHostname:- // We need to get the origin of the passed in domain in the event someone sets baseUrl- // to an url like https://example.com/deep/default/path and one of the found urls is an- // absolute relative path (/path/to/page)- return [{ glob: ignoreHttpSchema(`${url.origin}/**`) }];- case EnqueueStrategy.SameDomain: {- // Get the actual hostname from the base url- const baseUrlHostname = getDomain(url.hostname, { mixedInputs: false });-- if (baseUrlHostname) {- // We have a hostname, so we can use it to match all links on the page that point to it and any subdomains of it- url.hostname = baseUrlHostname;- return [- { glob: ignoreHttpSchema(`${url.origin.replace(baseUrlHostname, `*.${baseUrlHostname}`)}/**`) },- { glob: ignoreHttpSchema(`${url.origin}/**`) },- ];- }-- // We don't have a hostname (can happen for ips for instance), so reproduce the same behavior- // as SameDomainAndSubdomain- return [{ glob: ignoreHttpSchema(`${url.origin}/**`) }];- }- case EnqueueStrategy.SameOrigin:- // The same behavior as SameHostname, but respecting the protocol of the URL- return [{ glob: `${url.origin}/**` }];- case EnqueueStrategy.All:- default:- return [{ glob: `http{s,}://**` }];- }-}--/**- * Internal function that changes the enqueue glob patterns to match both http and https- */-function ignoreHttpSchema(pattern: string): string {- return pattern.replace(/^(https?):\/\//, 'http{s,}://');-}diff --git a/packages/utils/src/internals/url.ts b/packages/utils/src/internals/url.tsindex ecf73e3a1..4f1f904b3 100644--- a/packages/utils/src/internals/url.ts+++ b/packages/utils/src/internals/url.ts@@ -80,10 +80,8 @@ function normalizeHostname(hostname: string): string {/*** Check whether `target` matches `origin` under the given enqueue `strategy`. The URL scheme is not- * considered here (use {@apilink filterUrl} for the combined scheme + strategy check).- *- * The `enqueueLinks` implementation in `@crawlee/basic` matches the same strategies via glob patterns- * (see `packages/basic-crawler/src/internals/enqueue-links/enqueue-links.ts`) — keep the two in sync when changing either.+ * considered here (use {@apilink filterUrl} for the combined scheme + strategy check). This is the single+ * definition of the strategies, shared by `enqueueLinks`, sitemaps and robots.txt.*/export function matchesEnqueueStrategy(strategy: EnqueueStrategy | `${EnqueueStrategy}`,@@ -102,8 +100,8 @@ export function matchesEnqueueStrategy(return originDomain === getDomain(target.hostname, { mixedInputs: false });}- // No registrable domain (e.g. an IP address), fall back to comparing origins.- return target.origin === origin.origin;+ // No registrable domain (e.g. an IP address or `localhost`), fall back to the same hostname.+ return matchesEnqueueStrategy('same-hostname', target, origin);}case 'same-origin':// Compare scheme/host/port directly so a trailing-dot host is normalized.diff --git a/test/basic-crawler/enqueue-links/protocol-matching-based-on-strategy.test.ts b/test/basic-crawler/enqueue-links/protocol-matching-based-on-strategy.test.tsindex 052bc1fb9..1a23530f5 100644--- a/test/basic-crawler/enqueue-links/protocol-matching-based-on-strategy.test.ts+++ b/test/basic-crawler/enqueue-links/protocol-matching-based-on-strategy.test.ts@@ -27,7 +27,7 @@ const HTML = `* Runs `crawler.addRequests()` against the links extracted from `HTML`, resolved relative to `baseUrl` -* the address `enqueueLinks()` would normally anchor the strategy to - and returns the resulting URLs.*/-async function enqueuedUrls(strategy: EnqueueStrategy, baseUrl: string): Promise<Set<string>> {+async function enqueuedUrls(strategy: EnqueueStrategy, baseUrl: string, html = HTML): Promise<Set<string>> {const enqueued: Source[] = [];const requestQueue = await RequestQueue.open();const originalAddRequests = requestQueue.addRequests.bind(requestQueue);@@ -41,7 +41,7 @@ async function enqueuedUrls(strategy: EnqueueStrategy, baseUrl: string): Promise};const crawler = new CheerioCrawler({ requestManager: requestQueue });- const urls = extractUrlsFromCheerio(load(HTML), 'a', baseUrl);+ const urls = extractUrlsFromCheerio(load(html), 'a', baseUrl);await crawler.addRequests(urls, { baseUrl, strategy });return new Set(enqueued.map((item) => item.url!));@@ -69,4 +69,15 @@ describe('enqueueLinks() - matching and ignoring http/https protocol differencesnew Set(['https://example.com/first']),);});++ test('only SameOrigin respects the port', async () => {+ const html = `<a href="http://10.0.0.5:8080/a">a</a><a href="https://10.0.0.5/b">b</a>`;++ for (const strategy of [EnqueueStrategy.SameHostname, EnqueueStrategy.SameDomain]) {+ expect(await enqueuedUrls(strategy, 'http://10.0.0.5', html)).toEqual(+ new Set(['http://10.0.0.5:8080/a', 'https://10.0.0.5/b']),+ );+ }+ expect(await enqueuedUrls(EnqueueStrategy.SameOrigin, 'http://10.0.0.5', html)).toEqual(new Set());+ });});diff --git a/test/utils/url.test.ts b/test/utils/url.test.tsindex 3229dc981..f4e1f1a89 100644--- a/test/utils/url.test.ts+++ b/test/utils/url.test.ts@@ -10,8 +10,9 @@ describe('matchesEnqueueStrategy', () => {expect(match('all', 'https://other.test/page', 'http://example.com/sitemap.xml')).toBe(true);});- it('same-hostname matches only the exact host', () => {+ it('same-hostname matches only the exact host, regardless of port', () => {expect(match('same-hostname', 'http://example.com/a', 'http://example.com/sitemap.xml')).toBe(true);+ expect(match('same-hostname', 'http://example.com:8080/a', 'http://example.com/sitemap.xml')).toBe(true);expect(match('same-hostname', 'http://www.example.com/a', 'http://example.com/sitemap.xml')).toBe(false);});@@ -20,9 +21,16 @@ describe('matchesEnqueueStrategy', () => {expect(match('same-domain', 'http://example.org/a', 'http://example.com/sitemap.xml')).toBe(false);});+ it('same-domain on a host without a registrable domain falls back to same-hostname', () => {+ expect(match('same-domain', 'https://10.0.0.5/a', 'http://10.0.0.5/sitemap.xml')).toBe(true);+ expect(match('same-domain', 'http://localhost:3001/a', 'https://localhost:3000/sitemap.xml')).toBe(true);+ expect(match('same-domain', 'http://10.0.0.6/a', 'http://10.0.0.5/sitemap.xml')).toBe(false);+ });+it('same-origin requires matching scheme, host, and port', () => {expect(match('same-origin', 'http://example.com/a', 'http://example.com/sitemap.xml')).toBe(true);expect(match('same-origin', 'https://example.com/a', 'http://example.com/sitemap.xml')).toBe(false);+ expect(match('same-origin', 'http://example.com:8080/a', 'http://example.com/sitemap.xml')).toBe(false);});it('treats a trailing-dot FQDN host as equal to the bare host across strategies', () => {