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 6aadac21954f..c37540ca226b 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,10 @@ 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'> { + 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 365d7861e13b..b818bc855949 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 { @@ -293,19 +293,35 @@ export interface AdaptivePlaywrightCrawlerOptions< GetUserDataFromRequest >, StatisticStateExtension extends AdaptivePlaywrightCrawlerStatisticState = AdaptivePlaywrightCrawlerStatisticState, -> - extends - Omit< - BasicCrawlerOptions< - AdaptivePlaywrightCrawlerContext, - ContextExtension, - ExtendedContext, - Routes, - StatisticStateExtension - >, - 'preNavigationHooks' | 'postNavigationHooks' | 'contextPipelineBuilder' - >, - Pick { +> 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 @@ -499,10 +515,9 @@ export class AdaptivePlaywrightCrawler< extendContext, transactionalStorage, navigationTimeoutSecs, - launchContext, - headless, - browserPool, - remoteBrowser, + ignoreTlsErrors = false, + httpOptions, + browserOptions, ...rest } = options; @@ -540,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, @@ -604,6 +627,8 @@ 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, @@ -613,15 +638,18 @@ export class AdaptivePlaywrightCrawler< 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, }); 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..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'; @@ -14,6 +16,7 @@ import { MemoryStorageBackend, serviceLocator, } from '@crawlee/core'; +import { BaseHttpClient, FetchHttpClient } from '@crawlee/http-client'; import type { AdaptivePlaywrightCrawlerContext, AdaptivePlaywrightCrawlerOptions, @@ -36,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'; @@ -146,6 +150,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'); @@ -894,7 +902,11 @@ describe('AdaptivePlaywrightCrawler', () => { ); const crawler = await makeOneshotCrawler( - { requestHandler, renderingTypePredictor, launchContext: { launcher: playwright[browser] } }, + { + requestHandler, + renderingTypePredictor, + browserOptions: { launchContext: { launcher: playwright[browser] } }, + }, [url], ); @@ -1674,9 +1686,114 @@ 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 () => { + 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, + httpOptions: { 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([ + [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], + ])('forwards ignoreIframes: %s to the inner PlaywrightCrawler', async (ignoreIframes, expectedMatches) => { + const matches: number[] = []; + const crawler = await makeOneshotCrawler( + { + browserOptions: { 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 () => { @@ -1691,7 +1808,7 @@ describe('AdaptivePlaywrightCrawler', () => { { requestHandler: async () => {}, renderingTypePredictor, - launchContext: { userAgent: distinctiveUserAgent }, + browserOptions: { launchContext: { userAgent: distinctiveUserAgent } }, }, [`http://${HOSTNAME}:${port}/dynamic`], );