From 5565ac3fb6ea459a9b4a32ac2eac807b46e70237 Mon Sep 17 00:00:00 2001 From: Jan Buchar Date: Mon, 30 Nov 2026 19:05:12 +0100 Subject: [PATCH 1/2] fix(adaptive): Handle ignoreTlsErrors, additionalMimeTypes and ignoreIframes options --- docs/public-api/crawlee-playwright.api.md | 3 +- .../internals/adaptive-playwright-crawler.ts | 14 ++++- .../adaptive-playwright-crawler.test.ts | 61 +++++++++++++++++++ 3 files changed, 75 insertions(+), 3 deletions(-) diff --git a/docs/public-api/crawlee-playwright.api.md b/docs/public-api/crawlee-playwright.api.md index 6aadac21954f..643c1c37033a 100644 --- a/docs/public-api/crawlee-playwright.api.md +++ b/docs/public-api/crawlee-playwright.api.md @@ -22,6 +22,7 @@ import type { BrowserPoolOptions } from '@crawlee/browser-pool'; import type { BrowserType } from 'playwright'; import { Cheerio } from 'cheerio'; import { CheerioAPI } from 'cheerio'; +import type { CheerioCrawlerOptions } from '@crawlee/cheerio'; import { Configuration } from '@crawlee/browser'; import type { CrawlerRemoteBrowserOptions } from '@crawlee/browser'; import type { CrawlingContext } from '@crawlee/basic'; @@ -98,7 +99,7 @@ export interface AdaptivePlaywrightCrawlerContext, ExtendedContext extends AdaptivePlaywrightCrawlerContext = AdaptivePlaywrightCrawlerContext & ContextExtension, Routes extends Record = Record>, StatisticStateExtension extends AdaptivePlaywrightCrawlerStatisticState = AdaptivePlaywrightCrawlerStatisticState> extends Omit, 'preNavigationHooks' | 'postNavigationHooks' | 'contextPipelineBuilder'>, Pick { +export interface AdaptivePlaywrightCrawlerOptions, ExtendedContext extends AdaptivePlaywrightCrawlerContext = AdaptivePlaywrightCrawlerContext & ContextExtension, Routes extends Record = Record>, StatisticStateExtension extends AdaptivePlaywrightCrawlerStatisticState = AdaptivePlaywrightCrawlerStatisticState> extends Omit, 'preNavigationHooks' | 'postNavigationHooks' | 'contextPipelineBuilder'>, Pick, Pick { navigationTimeoutSecs?: number; postNavigationHooks?: AdaptivePostNavigationHook[]; preNavigationHooks?: AdaptiveHook[]; diff --git a/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts b/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts index 365d7861e13b..b945644e7927 100644 --- a/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts +++ b/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts @@ -25,7 +25,7 @@ import { Statistics, } from '@crawlee/basic'; import { CrawlingRequest, extractUrlsFromPage } from '@crawlee/browser'; -import type { CheerioCrawlingContext } from '@crawlee/cheerio'; +import type { CheerioCrawlerOptions, CheerioCrawlingContext } from '@crawlee/cheerio'; import { CheerioCrawler } from '@crawlee/cheerio'; import { ResponseWithUrl } from '@crawlee/http-client'; import type { @@ -305,7 +305,11 @@ export interface AdaptivePlaywrightCrawlerOptions< >, 'preNavigationHooks' | 'postNavigationHooks' | 'contextPipelineBuilder' >, - Pick { + Pick, + Pick< + PlaywrightCrawlerOptions, + 'launchContext' | 'headless' | 'browserPool' | 'remoteBrowser' | 'ignoreIframes' + > { /** * Timeout for the navigation phase of each attempt, in seconds, shared by the `preNavigationHooks`, the * navigation and the `postNavigationHooks`. Applies to both the HTTP-only and the browser attempt. When not @@ -503,6 +507,9 @@ export class AdaptivePlaywrightCrawler< headless, browserPool, remoteBrowser, + ignoreTlsErrors, + additionalMimeTypes, + ignoreIframes, ...rest } = options; @@ -609,6 +616,8 @@ export class AdaptivePlaywrightCrawler< postNavigationHooks, extendContext, navigationTimeoutSecs, + ignoreTlsErrors, + additionalMimeTypes, }); const browserCrawler = new PlaywrightCrawler({ @@ -622,6 +631,7 @@ export class AdaptivePlaywrightCrawler< headless, browserPool, remoteBrowser, + ignoreIframes, }); this.#staticCrawler = staticCrawler; diff --git a/test/core/crawlers/adaptive-playwright-crawler.test.ts b/test/core/crawlers/adaptive-playwright-crawler.test.ts index 646b1037c0e5..6ae24e8bc83f 100644 --- a/test/core/crawlers/adaptive-playwright-crawler.test.ts +++ b/test/core/crawlers/adaptive-playwright-crawler.test.ts @@ -14,6 +14,7 @@ import { MemoryStorageBackend, serviceLocator, } from '@crawlee/core'; +import { BaseHttpClient, FetchHttpClient } from '@crawlee/http-client'; import type { AdaptivePlaywrightCrawlerContext, AdaptivePlaywrightCrawlerOptions, @@ -146,6 +147,10 @@ describe('AdaptivePlaywrightCrawler', () => { res.status(200).type('text/plain').send('hello'); }); + app.get('/iframe', (_req, res) => { + res.status(200).send(``); + }); + app.get('/repeated-headers', (_req, res) => { res.cookie('a', '1'); res.cookie('b', '2'); @@ -1679,6 +1684,62 @@ describe('AdaptivePlaywrightCrawler', () => { ); }); + test('forwards HTTP options to the inner CheerioCrawler', async () => { + const captured: (boolean | undefined)[] = []; + const fetchClient = new FetchHttpClient(); + // Carries the BaseHttpClient prototype so the crawler's `z.instanceof` validation accepts it. + const capturingClient = Object.assign(Object.create(BaseHttpClient.prototype) as BaseHttpClient, { + sendRequest: async (request: globalThis.Request, options?: { ignoreTlsErrors?: boolean }) => { + captured.push(options?.ignoreTlsErrors); + return fetchClient.sendRequest(request, options); + }, + }); + const requestHandler = vi.fn(); + + const crawler = await makeOneshotCrawler( + { + httpClient: capturingClient, + ignoreTlsErrors: true, + additionalMimeTypes: ['text/plain'], + renderingTypePredictor: makeRiggedRenderingTypePredictor({ + renderingType: 'static', + detectionProbabilityRecommendation: 0, + }), + // Surface the HTTP-only attempt's error instead of falling back to a browser. + shouldPropagateError: () => true, + requestHandler, + }, + [`http://${HOSTNAME}:${port}/plain`], + ); + await crawler.run(); + + expect(requestHandler).toHaveBeenCalledTimes(1); + expect(captured).toEqual([true]); + }); + + test.each([ + [false, 1], + [true, 0], + ])('forwards ignoreIframes: %s to the inner PlaywrightCrawler', async (ignoreIframes, expectedMatches) => { + const matches: number[] = []; + const crawler = await makeOneshotCrawler( + { + ignoreIframes, + renderingTypePredictor: makeRiggedRenderingTypePredictor({ + renderingType: 'clientOnly', + detectionProbabilityRecommendation: 0, + }), + requestHandler: async ({ parseWithCheerio }) => { + matches.push((await parseWithCheerio())('#inner').length); + }, + }, + [`http://${HOSTNAME}:${port}/iframe`], + ); + await crawler.run(); + + expect(matches).toEqual([expectedMatches]); + }); + test('launchContext reaches the browser launched for the browser-rendering path', async () => { const renderingTypePredictor = makeRiggedRenderingTypePredictor({ renderingType: 'clientOnly', From 38049d44a4aec5dacfd32c0216b8656da160e9a5 Mon Sep 17 00:00:00 2001 From: Jan Buchar Date: Tue, 1 Dec 2026 13:36:48 +0100 Subject: [PATCH 2/2] Move options that only apply to one sub-crawler to a better named sub-bag --- .../adaptive-crawling/adaptive-crawling.mdx | 2 +- docs/public-api/crawlee-playwright.api.md | 5 +- docs/upgrading/upgrading-v4/upgrading-v4.md | 2 + .../internals/adaptive-playwright-crawler.ts | 80 ++++++++++++------- .../adaptive-playwright-crawler.test.ts | 70 ++++++++++++++-- 5 files changed, 119 insertions(+), 40 deletions(-) diff --git a/docs/guides/adaptive-crawling/adaptive-crawling.mdx b/docs/guides/adaptive-crawling/adaptive-crawling.mdx index d06d4cd8e399..af6278f93c48 100644 --- a/docs/guides/adaptive-crawling/adaptive-crawling.mdx +++ b/docs/guides/adaptive-crawling/adaptive-crawling.mdx @@ -184,7 +184,7 @@ preNavigationHooks: [ ], ``` -`launchContext`, `headless`, `browserPool` and `remoteBrowser` configure the browser side only. The remaining options, such as proxies, sessions and concurrency, apply to both. +Options that only make sense for one side are nested: `browserOptions` (`launchContext`, `headless`, `browserPool`, `remoteBrowser`, `ignoreIframes`) configures the browser, `httpOptions` (`additionalMimeTypes`) the HTTP-only requests. The remaining options, such as proxies, sessions, concurrency, `navigationTimeoutSecs` and `ignoreTlsErrors`, apply to both. The browser ignores TLS errors through Playwright's `ignoreHTTPSErrors` launch option, so `ignoreTlsErrors` can't be combined with `browserPool`, `remoteBrowser` or `launchContext.useIncognitoPages`. ## Monitoring diff --git a/docs/public-api/crawlee-playwright.api.md b/docs/public-api/crawlee-playwright.api.md index 643c1c37033a..c37540ca226b 100644 --- a/docs/public-api/crawlee-playwright.api.md +++ b/docs/public-api/crawlee-playwright.api.md @@ -99,7 +99,10 @@ export interface AdaptivePlaywrightCrawlerContext, ExtendedContext extends AdaptivePlaywrightCrawlerContext = AdaptivePlaywrightCrawlerContext & ContextExtension, Routes extends Record = Record>, StatisticStateExtension extends AdaptivePlaywrightCrawlerStatisticState = AdaptivePlaywrightCrawlerStatisticState> extends Omit, 'preNavigationHooks' | 'postNavigationHooks' | 'contextPipelineBuilder'>, Pick, Pick { +export interface AdaptivePlaywrightCrawlerOptions, ExtendedContext extends AdaptivePlaywrightCrawlerContext = AdaptivePlaywrightCrawlerContext & ContextExtension, Routes extends Record = Record>, StatisticStateExtension extends AdaptivePlaywrightCrawlerStatisticState = AdaptivePlaywrightCrawlerStatisticState> extends Omit, 'preNavigationHooks' | 'postNavigationHooks' | 'contextPipelineBuilder'> { + browserOptions?: Pick; + httpOptions?: Pick; + ignoreTlsErrors?: boolean; navigationTimeoutSecs?: number; postNavigationHooks?: AdaptivePostNavigationHook[]; preNavigationHooks?: AdaptiveHook[]; diff --git a/docs/upgrading/upgrading-v4/upgrading-v4.md b/docs/upgrading/upgrading-v4/upgrading-v4.md index c72fadbcc167..082154c50486 100644 --- a/docs/upgrading/upgrading-v4/upgrading-v4.md +++ b/docs/upgrading/upgrading-v4/upgrading-v4.md @@ -82,6 +82,8 @@ The purely mechanical renames, collected in one place. Where a row links to a se | `statistics.state.requestsFinished` (and the other `*Finished*` counters) | `requestsSucceeded` ([details](#finished-request-counters-are-renamed-to-succeeded)) | | `statistics.startJob()` / `finishJob()` / `failJob()` | `recordRequestStart()` / `recordRequestSuccess()` / `recordRequestFailure()` ([details](./statistics.md#the-request-recording-methods-are-renamed)) | | `browserPoolOptions` | `browserPool` + a `*BrowserPool()` factory ([details](#browserpooloptions-is-removed)) | +| `AdaptivePlaywrightCrawler` options `launchContext` / `headless` / `browserPool` / `remoteBrowser` / `ignoreIframes` | `browserOptions: { ... }` | +| `AdaptivePlaywrightCrawler` option `additionalMimeTypes` | `httpOptions: { additionalMimeTypes }` | | `gotScraping` (from `@crawlee/utils`) | `GotScrapingHttpClient` (`@crawlee/got-scraping-client`) | | Internal KVS keys (`SDK_*` and others) | `CRAWLEE_*` keys ([details](#internal-kvs-keys-renamed)) | | `ArgumentError` (from `ow`) | `ArgumentValidationError` ([details](#argument-validation-errors-use-zod)) | diff --git a/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts b/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts index b945644e7927..b818bc855949 100644 --- a/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts +++ b/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts @@ -293,23 +293,35 @@ export interface AdaptivePlaywrightCrawlerOptions< GetUserDataFromRequest >, StatisticStateExtension extends AdaptivePlaywrightCrawlerStatisticState = AdaptivePlaywrightCrawlerStatisticState, -> - extends - Omit< - BasicCrawlerOptions< - AdaptivePlaywrightCrawlerContext, - ContextExtension, - ExtendedContext, - Routes, - StatisticStateExtension - >, - 'preNavigationHooks' | 'postNavigationHooks' | 'contextPipelineBuilder' - >, - Pick, - Pick< - PlaywrightCrawlerOptions, - 'launchContext' | 'headless' | 'browserPool' | 'remoteBrowser' | 'ignoreIframes' - > { +> extends Omit< + BasicCrawlerOptions< + AdaptivePlaywrightCrawlerContext, + ContextExtension, + ExtendedContext, + Routes, + StatisticStateExtension + >, + 'preNavigationHooks' | 'postNavigationHooks' | 'contextPipelineBuilder' +> { + /** + * If set to `true`, TLS/SSL certificate errors are ignored in both attempts: see + * {@apilink HttpCrawlerOptions.ignoreTlsErrors} for the HTTP-only one, the browser gets Playwright's + * `ignoreHTTPSErrors` launch option. Can't be combined with `browserOptions.browserPool`, + * `browserOptions.remoteBrowser` or `browserOptions.launchContext.useIncognitoPages`, which don't use the launch options. + * + * @default false + */ + ignoreTlsErrors?: boolean; + + /** Options of the HTTP-only attempt, forwarded to its {@apilink CheerioCrawler}. */ + httpOptions?: Pick; + + /** Options of the browser attempt, forwarded to its {@apilink PlaywrightCrawler}. */ + browserOptions?: Pick< + PlaywrightCrawlerOptions, + 'launchContext' | 'headless' | 'browserPool' | 'remoteBrowser' | 'ignoreIframes' + >; + /** * Timeout for the navigation phase of each attempt, in seconds, shared by the `preNavigationHooks`, the * navigation and the `postNavigationHooks`. Applies to both the HTTP-only and the browser attempt. When not @@ -503,13 +515,9 @@ export class AdaptivePlaywrightCrawler< extendContext, transactionalStorage, navigationTimeoutSecs, - launchContext, - headless, - browserPool, - remoteBrowser, - ignoreTlsErrors, - additionalMimeTypes, - ignoreIframes, + ignoreTlsErrors = false, + httpOptions, + browserOptions, ...rest } = options; @@ -547,6 +555,14 @@ export class AdaptivePlaywrightCrawler< ); } + const { browserPool, remoteBrowser, launchContext } = browserOptions ?? {}; + if (ignoreTlsErrors && (browserPool || remoteBrowser || launchContext?.useIncognitoPages)) { + throw new Error( + 'AdaptivePlaywrightCrawler: `ignoreTlsErrors` cannot be combined with `browserPool`, `remoteBrowser` ' + + 'or `launchContext.useIncognitoPages` - configure the browser to ignore TLS errors yourself.', + ); + } + super({ ...rest, errorHandler, @@ -611,27 +627,29 @@ export class AdaptivePlaywrightCrawler< // each hook's overrides at runtime regardless of the static type. const staticCrawler = new CheerioCrawler({ ...rest, + ...httpOptions, + ignoreTlsErrors, statistics: new Statistics({ persistenceOptions: { enable: false } }), preNavigationHooks, postNavigationHooks, extendContext, navigationTimeoutSecs, - ignoreTlsErrors, - additionalMimeTypes, }); const browserCrawler = new PlaywrightCrawler({ ...rest, + ...browserOptions, + ...(ignoreTlsErrors && { + launchContext: { + ...launchContext, + launchOptions: { ...launchContext?.launchOptions, ignoreHTTPSErrors: true }, + }, + }), statistics: new Statistics({ persistenceOptions: { enable: false } }), preNavigationHooks: preNavigationHooks as unknown as PlaywrightHook[], postNavigationHooks: postNavigationHooks as unknown as PlaywrightHook[], extendContext, navigationTimeoutSecs, - launchContext, - headless, - browserPool, - remoteBrowser, - ignoreIframes, }); this.#staticCrawler = staticCrawler; diff --git a/test/core/crawlers/adaptive-playwright-crawler.test.ts b/test/core/crawlers/adaptive-playwright-crawler.test.ts index 6ae24e8bc83f..1bfa204d00ec 100644 --- a/test/core/crawlers/adaptive-playwright-crawler.test.ts +++ b/test/core/crawlers/adaptive-playwright-crawler.test.ts @@ -1,5 +1,7 @@ +import { once } from 'node:events'; import { readFile } from 'node:fs/promises'; import type { Server } from 'node:http'; +import { createServer as createHttpsServer } from 'node:https'; import type { AddressInfo } from 'node:net'; import { Statistics } from '@crawlee/basic'; @@ -37,6 +39,7 @@ import type { Dictionary } from '@crawlee/types'; import { sleep } from 'crawlee'; import express from 'express'; import playwright from 'playwright'; +import { generate } from 'selfsigned'; import { z } from 'zod'; import { startExpressAppPromise } from '../../shared/_helper.js'; @@ -899,7 +902,11 @@ describe('AdaptivePlaywrightCrawler', () => { ); const crawler = await makeOneshotCrawler( - { requestHandler, renderingTypePredictor, launchContext: { launcher: playwright[browser] } }, + { + requestHandler, + renderingTypePredictor, + browserOptions: { launchContext: { launcher: playwright[browser] } }, + }, [url], ); @@ -1679,9 +1686,12 @@ describe('AdaptivePlaywrightCrawler', () => { test('forwards browser options to the inner PlaywrightCrawler', () => { // `headless` can only collide with `browserPool` in the strict-object validation of the inner // `PlaywrightCrawler` if both options actually reached it - proving the options are wired through. - expect(() => new AdaptivePlaywrightCrawler({ browserPool: playwrightBrowserPool(), headless: false })).toThrow( - 'PlaywrightCrawler: `headless` cannot be combined with `browserPool`', - ); + expect( + () => + new AdaptivePlaywrightCrawler({ + browserOptions: { browserPool: playwrightBrowserPool(), headless: false }, + }), + ).toThrow('PlaywrightCrawler: `headless` cannot be combined with `browserPool`'); }); test('forwards HTTP options to the inner CheerioCrawler', async () => { @@ -1700,7 +1710,7 @@ describe('AdaptivePlaywrightCrawler', () => { { httpClient: capturingClient, ignoreTlsErrors: true, - additionalMimeTypes: ['text/plain'], + httpOptions: { additionalMimeTypes: ['text/plain'] }, renderingTypePredictor: makeRiggedRenderingTypePredictor({ renderingType: 'static', detectionProbabilityRecommendation: 0, @@ -1717,6 +1727,52 @@ describe('AdaptivePlaywrightCrawler', () => { expect(captured).toEqual([true]); }); + test.each([ + [true, 'handled'], + [false, 'failed'], + ])('ignoreTlsErrors: %s reaches the browser attempt', async (ignoreTlsErrors, expected) => { + const pems = await generate([{ name: 'commonName', value: 'localhost' }], { keyType: 'ec' }); + const httpsServer = createHttpsServer({ key: pems.private, cert: pems.cert }, (_req, res) => { + res.writeHead(200, { 'content-type': 'text/html' }).end('ok'); + }); + await once(httpsServer.listen(0), 'listening'); + + const outcomes: string[] = []; + try { + const crawler = await makeOneshotCrawler( + { + ignoreTlsErrors, + renderingTypePredictor: makeRiggedRenderingTypePredictor({ + renderingType: 'clientOnly', + detectionProbabilityRecommendation: 0, + }), + requestHandler: async () => { + outcomes.push('handled'); + }, + failedRequestHandler: async () => { + outcomes.push('failed'); + }, + }, + [`https://localhost:${(httpsServer.address() as AddressInfo).port}/`], + ); + await crawler.run(); + } finally { + httpsServer.close(); + } + + expect(outcomes).toEqual([expected]); + }); + + test.each([ + ['browserPool', { browserPool: playwrightBrowserPool() }], + ['remoteBrowser', { remoteBrowser: { endpoint: 'ws://localhost:1' } }], + ['useIncognitoPages', { launchContext: { useIncognitoPages: true } }], + ] as const)('rejects ignoreTlsErrors combined with %s', (_name, browserOptions) => { + expect(() => new AdaptivePlaywrightCrawler({ ignoreTlsErrors: true, browserOptions })).toThrow( + '`ignoreTlsErrors` cannot be combined', + ); + }); + test.each([ [false, 1], [true, 0], @@ -1724,7 +1780,7 @@ describe('AdaptivePlaywrightCrawler', () => { const matches: number[] = []; const crawler = await makeOneshotCrawler( { - ignoreIframes, + browserOptions: { ignoreIframes }, renderingTypePredictor: makeRiggedRenderingTypePredictor({ renderingType: 'clientOnly', detectionProbabilityRecommendation: 0, @@ -1752,7 +1808,7 @@ describe('AdaptivePlaywrightCrawler', () => { { requestHandler: async () => {}, renderingTypePredictor, - launchContext: { userAgent: distinctiveUserAgent }, + browserOptions: { launchContext: { userAgent: distinctiveUserAgent } }, }, [`http://${HOSTNAME}:${port}/dynamic`], );