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.

fix: fetch robots.txt through the crawler's HTTP client like a browser (#4218)

Muhammad Haadhee Sheeraz Miane4c89640d25d
diff --git a/docs/public-api/crawlee-utils.api.md b/docs/public-api/crawlee-utils.api.md
index 136d08028..15b4ac507 100644
--- a/docs/public-api/crawlee-utils.api.md
+++ b/docs/public-api/crawlee-utils.api.md
@@ -9,6 +9,7 @@ import type { BaseHttpClient } from '@crawlee/http-client';
import type { CheerioAPI } from 'cheerio';
import type { CrawleeLogger } from '@crawlee/types';
import type { Dictionary } from '@crawlee/types';
+import type { ISession } from '@crawlee/types';
export { ArgumentValidationError }
@@ -161,6 +162,7 @@ export class RobotsTxtFile {
timeoutMillis?: number;
proxyUrl?: string;
httpClient?: BaseHttpClient;
+ session?: ISession;
logger?: CrawleeLogger;
}): Promise<RobotsTxtFile>;
static from(url: string, content: string, proxyUrl?: string): RobotsTxtFile;
diff --git a/packages/basic-crawler/src/internals/basic-crawler.ts b/packages/basic-crawler/src/internals/basic-crawler.ts
index 03fb0d41e..1fd56aea5 100644
--- a/packages/basic-crawler/src/internals/basic-crawler.ts
+++ b/packages/basic-crawler/src/internals/basic-crawler.ts
@@ -2555,7 +2555,15 @@ export class BasicCrawler<
return cachedRobotsTxtFile;
}
- const robotsTxtFile = await RobotsTxtFile.find(url, { logger: this.log });
+ // Fetch robots.txt the way pages are fetched: through the crawler's HTTP client, with a session's browser
+ // fingerprint and proxy. Sites with bot protection answer a bare request with 4xx or 5xx, and that status
+ // alone would then decide whether everything is allowed or disallowed.
+ const robotsTxtFile = await RobotsTxtFile.find(url, {
+ httpClient: this.httpClient,
+ session: await this.sessionPool.getSession(),
+ timeoutMillis: 30_000,
+ logger: this.log,
+ });
this.#robotsTxtFileCache.add(origin, robotsTxtFile);
return robotsTxtFile;
diff --git a/packages/utils/src/internals/robots.ts b/packages/utils/src/internals/robots.ts
index 2550a9b97..3a13a6daa 100644
--- a/packages/utils/src/internals/robots.ts
+++ b/packages/utils/src/internals/robots.ts
@@ -1,6 +1,6 @@
import { FetchHttpClient } from '@crawlee/http-client';
import type { BaseHttpClient } from '@crawlee/http-client';
-import type { CrawleeLogger } from '@crawlee/types';
+import type { CrawleeLogger, ISession } from '@crawlee/types';
import type { Robot } from 'robots-parser';
import robotsParser from 'robots-parser';
@@ -59,6 +59,7 @@ export class RobotsTxtFile {
* @param [options.signal] an AbortSignal to cancel the request
* @param [options.timeoutMillis] timeout in milliseconds for the request
* @param [options.proxyUrl] a proxy to be used for fetching the robots.txt file
+ * @param [options.session] a session whose fingerprint and cookies the request uses, like a page request would
*/
static async find(
url: string,
@@ -67,6 +68,7 @@ export class RobotsTxtFile {
timeoutMillis?: number;
proxyUrl?: string;
httpClient?: BaseHttpClient;
+ session?: ISession;
logger?: CrawleeLogger;
},
): Promise<RobotsTxtFile> {
@@ -95,12 +97,14 @@ export class RobotsTxtFile {
timeoutMillis?: number;
proxyUrl?: string;
httpClient?: BaseHttpClient;
+ session?: ISession;
logger?: CrawleeLogger;
},
): Promise<RobotsTxtFile> {
- const { proxyUrl, logger, httpClient = new FetchHttpClient() } = options || {};
+ const { proxyUrl, logger, session, httpClient = new FetchHttpClient() } = options || {};
const response = await httpClient.sendRequest(new Request(url, { method: 'GET' }), {
+ session,
proxyUrl,
timeoutMillis: options?.timeoutMillis,
signal: options?.signal,
diff --git a/test/core/crawlers/basic-crawler.test.ts b/test/core/crawlers/basic-crawler.test.ts
index 5dbf533d8..40becff12 100644
--- a/test/core/crawlers/basic-crawler.test.ts
+++ b/test/core/crawlers/basic-crawler.test.ts
@@ -46,7 +46,7 @@ import {
} from '@crawlee/basic';
import type { StorageTransaction } from '@crawlee/core';
import { currentStorageTransaction, MemoryStorageBackend } from '@crawlee/core';
-import { BaseHttpClient } from '@crawlee/http-client';
+import { BaseHttpClient, FetchHttpClient } from '@crawlee/http-client';
import { FileSystemStorageBackend } from '@crawlee/fs-storage';
import type { Dictionary, ISession, ProxyInfo } from '@crawlee/types';
import { RobotsTxtFile, sleep } from '@crawlee/utils';
@@ -3175,6 +3175,62 @@ describe('BasicCrawler', () => {
expect(addRequestsBatchedSpy).toHaveBeenCalledOnce();
});
+ test('fetches robots.txt with browser-like headers through the crawler http client', async () => {
+ // Bot protection: only browser-like clients get the real robots.txt, others get a 403.
+ const server = http.createServer((req, res) => {
+ if (req.url !== '/robots.txt') {
+ res.writeHead(200).end();
+ } else if (req.headers['user-agent']?.includes('Mozilla')) {
+ res.end('User-agent: *\nDisallow: /private\n');
+ } else {
+ res.writeHead(403).end();
+ }
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const { port } = server.address() as AddressInfo;
+
+ const handled: string[] = [];
+ const crawler = new BasicCrawler({
+ respectRobotsTxtFile: true,
+ requestHandler: async ({ request }) => {
+ handled.push(new URL(request.url).pathname);
+ },
+ });
+
+ try {
+ await crawler.run([`http://127.0.0.1:${port}/public`, `http://127.0.0.1:${port}/private`]);
+ } finally {
+ server.close();
+ }
+
+ expect(handled).toEqual(['/public']);
+ });
+
+ test('fetches robots.txt through the proxy of a crawler session', async () => {
+ const proxyUrl = 'http://proxy.example.com:8000';
+ const httpClient = new FetchHttpClient();
+ const sendRequest = vitest
+ .spyOn(httpClient, 'sendRequest')
+ .mockResolvedValue(new Response('User-agent: *\nDisallow: /private\n'));
+
+ const handled: string[] = [];
+ const crawler = new BasicCrawler({
+ respectRobotsTxtFile: true,
+ httpClient,
+ proxyConfiguration: new ProxyConfiguration({ proxyUrls: [proxyUrl] }),
+ requestHandler: async ({ request }) => {
+ handled.push(new URL(request.url).pathname);
+ },
+ });
+
+ await crawler.run(['https://example.com/public', 'https://example.com/private']);
+
+ expect(sendRequest).toHaveBeenCalledOnce();
+ expect(sendRequest.mock.calls[0][1]?.session?.proxyInfo?.url).toBe(proxyUrl);
+ expect(sendRequest.mock.calls[0][1]?.timeoutMillis).toBeGreaterThan(0);
+ expect(handled).toEqual(['/public']);
+ });
+
describe('robots.txt crawl-delay', () => {
const crawlerWithCrawlDelay = (options: Partial<BasicCrawlerOptions>) =>
new (class MockedRobotsTxtCrawler extends BasicCrawler {