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: refactor `requestAsBrowser` to Got 12 (#1111)
Ondra Urbanef9a4ad32701
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 457408828..c99553ac4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,3 +1,7 @@+2.0.2 / BETA+====================+- **BREAKING IN EDGE CASES** - We disabled `forceUrlEncoding` in `requestAsBrowser` because we found out that recent versions of the underlying HTTP client `got` already encode URLs and `forceUrlEncoding` could lead to weird behavior. We think of this as fixing a bug, so we're not bumping the major version.+2.0.2 / 2021/08/12====================- Fix serialization issues in `CheerioCrawler` caused by parser conflicts in recent versions of `cheerio`.diff --git a/package.json b/package.jsonindex e721ebe0d..02206d5c7 100644--- a/package.json+++ b/package.json@@ -67,7 +67,7 @@"content-type": "^1.0.4","express": "^4.17.1","fs-extra": "^10.0.0",- "got-scraping": "2.0.1",+ "got-scraping": "2.1.3-beta.1","htmlparser2": "^6.1.0","iconv-lite": "^0.6.3","jquery": "^3.6.0",diff --git a/src/crawlers/cheerio_crawler.js b/src/crawlers/cheerio_crawler.jsindex 82e658437..fd3453ce7 100644--- a/src/crawlers/cheerio_crawler.js+++ b/src/crawlers/cheerio_crawler.js@@ -718,7 +718,6 @@ class CheerioCrawler extends BasicCrawler {headers: { ...request.headers, ...requestAsBrowserOptions.headers },ignoreSslErrors: this.ignoreSslErrors,proxyUrl,- useCaseSensitiveHeaders: true,timeoutSecs: this.requestTimeoutMillis / 1000,...requestAsBrowserOptions,stream: true,diff --git a/src/utils_request.js b/src/utils_request.jsindex a77b0dba5..fb33c5aea 100644--- a/src/utils_request.js+++ b/src/utils_request.js@@ -49,8 +49,6 @@ import { IncomingMessage } from 'http';* expect HTTP2 connections, because browsers use HTTP2 by default. It will automatically downgrade* to HTTP/1.1 for websites that do not support HTTP2. For Node 10 this option is always set to `false`* because Node 10 does not support HTTP2 very well. Upgrade to Node 12 for better performance.- * @property {boolean} [forceUrlEncoding]- * Automatically encode URLs via `encodeURI()` before resolving them.*//**@@ -121,7 +119,6 @@ export const requestAsBrowser = async (options = {}) => {headerGeneratorOptions: ow.optional.object,stream: ow.optional.boolean,decodeBody: ow.optional.boolean,- forceUrlEncoding: ow.optional.boolean,}));ow(options, 'RequestAsBrowserOptions', ow.object.validate((opts) => ({@@ -132,10 +129,9 @@ export const requestAsBrowser = async (options = {}) => {// We created the `got-scraping` package which replaced underlying @apify/http-request.// At the same time, we want users to be able to use requestAsBrowser without breaking changes.// So we do a lot of property mapping here, to make sure that everything works as expected.- // TODO Update this with SDK v2 and use `got-scraping` API directly.+ // TODO Update this with SDK v3 and use `got-scraping` API directly.const {payload, // alias for body to allow direct passing of our Request objects- proxyUrl,json,headerGeneratorOptions,languageCode = 'en',@@ -149,15 +145,14 @@ export const requestAsBrowser = async (options = {}) => {throwOnHttpErrors = false,stream = false,decodeBody = true,- forceUrlEncoding,+ forceUrlEncoding, // TODO remove in v3. It's not used, but we keep it here to prevent validation errors in got....gotParams} = options;const gotScrapingOptions = {- proxyUrl,insecureHTTPParser: useInsecureHttpParser,http2: useHttp2,- timeout: timeoutSecs * 1000,+ timeout: { request: timeoutSecs * 1000 },throwHttpErrors: throwOnHttpErrors,isStream: stream,decompress: decodeBody,@@ -165,15 +160,18 @@ export const requestAsBrowser = async (options = {}) => {// got interface a priority over our requestAsBrowser one.// E.g. { isStream: false, stream: true } should produce { isStream: false }....gotParams,+ https: {+ ...gotParams.https,+ rejectUnauthorized: !ignoreSslErrors,+ },};- // TODO remove when we drop support for Node 10- ensureValidConfigForNode10(gotScrapingOptions);+ // Encode the URL if necessary+ gotScrapingOptions.url = fixUrl(gotScrapingOptions.url);- // Order is important for payload and json.+ // Order is importantnormalizePayloadOption(payload, gotScrapingOptions);normalizeJsonOption(json, gotScrapingOptions);- normalizeSslErrorHandling(ignoreSslErrors, gotScrapingOptions);ensureCorrectHttp2Headers(gotScrapingOptions);maybeAddAbortHook(abortFunction, gotScrapingOptions);if (!headerGeneratorOptions) {@@ -186,17 +184,16 @@ export const requestAsBrowser = async (options = {}) => {gotScrapingOptions.headerGeneratorOptions = headerGeneratorOptions;}- if (forceUrlEncoding) {- gotScrapingOptions.url = encodeURI(gotScrapingOptions.url);- }-+ // Return the promise directlyif (!gotScrapingOptions.isStream) {return gotScraping(gotScrapingOptions);}// abortFunction must be handled separately for streams :(- const duplexStream = await gotScraping(gotScrapingOptions);+ const duplexStream = gotScraping(gotScrapingOptions);+ensureRequestIsDispatched(duplexStream, gotScrapingOptions);+return new Promise((resolve, reject) => {duplexStream.on('error', reject)@@ -220,15 +217,50 @@ export const requestAsBrowser = async (options = {}) => {});};-function ensureValidConfigForNode10(gotScrapingOptions) {- if (process.version.startsWith('v10')) {- if (gotScrapingOptions.http2 === true) {- // Using log.deprecated to log only once.- log.deprecated('utils.requestAsBrowser does not support HTTP2 on Node 10. Please upgrade to Node 12+ or set useHttp2 to false.');+/**+ * Fixes malformed URIs. Takes ~13s per 1M executions.+ * @example fixUrl('https://example.com/%cf') => 'https://example.com/%EF%BF%BD'+ * @example fixUrl('https://example.com/%xx') => 'https://example.com/%25xx'+ * @example fixUrl('https://example.com/%0fexample%cc%0f') => 'https://example.com/%0Fexample%EF%BF%BD%0F'+ * @see https://tc39.es/ecma262/multipage/global-object.html#sec-decodeuri-encodeduri+ * @param {string} url+ * @private+ */+function fixUrl(url) {+ const hexChars = '0123456789abcdefABCDEF';+ let chunks = '';++ let index = url.indexOf('%');+ while (index !== -1 && index < url.length) {+ const start = index;++ do {+ const buffer = url.slice(index + 1, index + 3);++ if (hexChars.indexOf(buffer[0]) !== -1 && hexChars.indexOf(buffer[1]) !== -1) {+ chunks += buffer;++ index += 3;+ } else {+ chunks += '25'; // %++ index += 1;+ break;+ }+ } while (url[index] === '%');++ if (chunks.length) {+ const encoded = encodeURI(Buffer.from(chunks, 'hex').toString());+ url = `${url.slice(0, start)}${encoded}${url.slice(index)}`;++ index += encoded.length;+ chunks = '';}- gotScrapingOptions.http2 = false;- gotScrapingOptions.ciphers = undefined;++ index = url.indexOf('%', index);}++ return url;}/**@@ -276,10 +308,15 @@ function normalizePayloadOption(payload, gotScrapingOptions) {function normalizeJsonOption(json, gotScrapingOptions) {// If it's a boolean, then it's the old requestAsBrowser API.// If it's true, it means the user expects a JSON response.+ const deprecationMessage = `"options.json" of type: Boolean is deprecated.`+ + 'If you expect a JSON response, use "options.responseType = \'json\'"'+ + 'Use "options.json" with a plain object to provide a JSON body.';if (json === true) {+ log.deprecated(deprecationMessage);gotScrapingOptions.responseType = 'json';- gotScrapingOptions.ciphers = undefined;+ gotScrapingOptions.https.ciphers = undefined;} else if (json === false) {+ log.deprecated(deprecationMessage);// Do nothing, it means the user expects something else than JSON.} else {// If it's something else, we let `got` handle it as a request body.@@ -287,20 +324,6 @@ function normalizeJsonOption(json, gotScrapingOptions) {}}-/**- * @param {boolean} ignoreSslErrors- * @param {GotScrapingOptions} gotScrapingOptions- * @ignore- * @private- */-function normalizeSslErrorHandling(ignoreSslErrors, gotScrapingOptions) {- if (gotScrapingOptions.https) {- gotScrapingOptions.https.rejectUnauthorized = !ignoreSslErrors;- } else {- gotScrapingOptions.https = { rejectUnauthorized: !ignoreSslErrors };- }-}-/*** 'connection' and 'host' headers are forbidden when using HTTP2. We delete* them from user-provided headers because we switched the default from HTTP1 to 2.@@ -309,11 +332,17 @@ function normalizeSslErrorHandling(ignoreSslErrors, gotScrapingOptions) {* @private*/function ensureCorrectHttp2Headers(gotScrapingOptions) {- if (gotScrapingOptions.http2) {- delete gotScrapingOptions.headers?.connection;- delete gotScrapingOptions.headers?.Connection;- delete gotScrapingOptions.headers?.host;- delete gotScrapingOptions.headers?.Host;+ if (gotScrapingOptions.http2 && gotScrapingOptions.headers) {+ gotScrapingOptions.headers = { ...gotScrapingOptions.headers };++ // eslint-disable-next-line no-restricted-syntax, guard-for-in+ for (const key in gotScrapingOptions.headers) {+ const lkey = key.toLowerCase();++ if (lkey === 'connection' || lkey === 'host') {+ delete gotScrapingOptions.headers[key];+ }+ }}}@@ -338,12 +367,16 @@ function maybeAddAbortHook(abortFunction, gotScrapingOptions) {return response;};- const abortRequestOptions = {- hooks: {- afterResponse: [abortHook],- },+ const { hooks } = gotScrapingOptions;+ const fixedHooks = {+ ...hooks,+ afterResponse: [+ ...((hooks && hooks.afterResponse) || []),+ abortHook,+ ],};- gotScrapingOptions = gotScraping.mergeOptions(gotScraping.defaults.options, gotScrapingOptions, abortRequestOptions);++ gotScrapingOptions.hooks = fixedHooks;}/**@@ -368,11 +401,36 @@ function ensureRequestIsDispatched(duplexStream, gotScrapingOptions) {* @private*/function logDeprecatedOptions(options) {- const deprecatedOptions = ['languageCode', 'countryCode', 'useMobileVersion'];+ const deprecatedOptions = [+ // 'json' is handled in the JSON handler, because it has a conflict of types+ ['languageCode', 'headerGeneratorOptions.locales'],+ ['countryCode', 'headerGeneratorOptions.locales'],+ ['useMobileVersion', 'headerGeneratorOptions.devices'],+ ['payload', 'body'],+ ['useHttp2', 'http2'],+ ['stream', 'isStream'],+ ['decodeBody', 'decompress'],+ ['throwOnHttpErrors', 'throwHttpErrors'],+ ['timeoutSecs', 'timeout.request'],+ ['ignoreSslErrors', 'https.rejectUnauthorized'],+ ['abortFunction'], // custom message below+ ];- for (const deprecatedOption of deprecatedOptions) {- if (options.hasOwnProperty(deprecatedOption)) {- log.deprecated(`"options.${deprecatedOption}" is deprecated. Use "options.headerGeneratorOptions" instead.`);+ for (const [deprecatedOption, newOption] of deprecatedOptions) {+ if (options[deprecatedOption] !== undefined) {+ // This will log only for the first property thanks to log.deprecated logging only once.+ const initialMessage = 'requestAsBrowser internal implementation has been replaced with the got-scraping module. '+ + 'To make the switch without breaking changes, we mapped all existing options to the got-scraping options. '+ + 'This mapping will be removed in SDK v3 and we advise you to update your code using the hints below: ';+ log.deprecated(initialMessage);++ if (deprecatedOption === 'abortFunction') {+ log.deprecated(`"options.${deprecatedOption}" is deprecated.`+ + 'Use a request cancellation process appropriate for your request type.'+ + 'Either a Stream or a Promise. See Got documentation for more info: https://github.com/sindresorhus/got');+ } else {+ log.deprecated(`"options.${deprecatedOption}" is deprecated. Use "options.${newOption}" instead.`);+ }}}}@@ -397,11 +455,18 @@ function addResponsePropertiesToStream(stream, response) {'request',];- properties.forEach((prop) => {- if (stream[prop] === undefined) {+ response.on('end', () => {+ Object.assign(stream.rawTrailers, response.rawTrailers);+ Object.assign(stream.trailers, response.trailers);++ stream.complete = response.complete;+ });++ for (const prop of properties) {+ if (!(prop in stream)) {stream[prop] = response[prop];}- });+ }return stream;}diff --git a/test/crawlers/cheerio_crawler.test.js b/test/crawlers/cheerio_crawler.test.jsindex f3ecb36b7..fc586d1bb 100644--- a/test/crawlers/cheerio_crawler.test.js+++ b/test/crawlers/cheerio_crawler.test.js@@ -131,10 +131,6 @@ app.get('/timeout', async (req, res) => {res.type('html').send('<div>TEST</div>');});-app.get('/proxy', (req, res) => {- res.type('html').send('<title>from proxy</title>');-});-/* eslint-disable no-underscore-dangle */describe('CheerioCrawler', () => {let logLevel;@@ -147,6 +143,18 @@ describe('CheerioCrawler', () => {server = await startExpressAppPromise(app, 0);port = server.address().port; //eslint-disable-linelocalStorageEmulator = new LocalStorageDirEmulator();++ server.on('connect', (_request, socket) => {+ socket.write(`HTTP/1.1 200 Connection Established\r\n\r\n`);++ socket.resume();++ setTimeout(() => {+ const body = 'from proxy';++ socket.end(`HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-length: ${body.length}\r\n\r\n${body}`);+ }, 100);+ });});beforeEach(async () => {@@ -262,11 +270,6 @@ describe('CheerioCrawler', () => {maxConcurrency: 2,handlePageFunction,handleFailedRequestFunction: ({ request }) => failed.push(request),- preNavigationHooks: [- (_, gotoOptions) => {- gotoOptions.forceUrlEncoding = true;- },- ],});await cheerioCrawler.run();@@ -276,7 +279,7 @@ describe('CheerioCrawler', () => {expect(processed[0].loadedUrl).toBe(`http://${HOST}:${port}/mirror?q=abc`);expect(processed[1].loadedUrl).toBe(`http://${HOST}:${port}/mirror?q=%25`);- expect(processed[2].loadedUrl).toBe(`http://${HOST}:${port}/mirror?q=%25cf`);+ expect(processed[2].loadedUrl).toBe(`http://${HOST}:${port}/mirror?q=%EF%BF%BD`);});test('postResponseFunction should work', async () => {@@ -689,11 +692,12 @@ describe('CheerioCrawler', () => {describe('proxy', () => {beforeEach(async () => {- jest.clearAllMocks();+ // Do not use clearAllMocks: https://github.com/facebook/jest/issues/7136+ jest.restoreAllMocks();});test('should work with Apify Proxy configuration', async () => {- const proxyUrl = `http://${HOST}:${port}/proxy`;+ const proxyUrl = `http://${HOST}:${port}/`;const proxyConfiguration = await Apify.createProxyConfiguration({proxyUrls: [proxyUrl],});diff --git a/test/utils_request.test.js b/test/utils_request.test.jsindex 11080a69a..68beb6d73 100644--- a/test/utils_request.test.js+++ b/test/utils_request.test.js@@ -104,28 +104,25 @@ describe('Apify.utils_request', () => {});const testQueries = [- ['abc', 'abc', true],- ['abc', 'abc', false],- ['%20', ' ', false],- ['%cf', '%cf', true],- ['helios-–-the-primordial-sun', 'helios-–-the-primordial-sun', true],- ['helios-%E2%80%93-the-primordial-sun', 'helios-–-the-primordial-sun', false],+ ['abc', 'abc'],+ ['%20', ' '],+ ['%cf', '�'],+ ['helios-–-the-primordial-sun', 'helios-–-the-primordial-sun'],+ ['helios-%E2%80%93-the-primordial-sun', 'helios-–-the-primordial-sun'],];- test.each(testQueries)(`it works with not encoded urls: '%s' (regular)`, async (query, decoded, forceEncode) => {+ test.each(testQueries)(`it works with not encoded urls: '%s' (regular)`, async (query, decoded) => {const response = await requestAsBrowser({url: `http://${HOSTNAME}:${port}/test-encoding/?q=${query}`,- forceUrlEncoding: forceEncode,});expect(response.statusCode).toBe(200);expect(JSON.parse(response.body).q).toBe(decoded);});- test.each(testQueries)(`it works with not encoded urls: '%s' (stream)`, async (query, decoded, forceEncode) => {+ test.each(testQueries)(`it works with not encoded urls: '%s' (stream)`, async (query, decoded) => {const response = await requestAsBrowser({url: `http://${HOSTNAME}:${port}/test-encoding/?q=${query}`,stream: true,- forceUrlEncoding: forceEncode,});const chunks = [];@@ -226,11 +223,23 @@ describe('Apify.utils_request', () => {bar: 'BAZ',},useHttp2: false,+ responseType: 'json',};const response = await requestAsBrowser(options);expect(response.statusCode).toBe(200);- expect(response.request.options.headers).toMatchObject(options.headers);++ // Split an array into chunks of two+ const entries = response.body.reduce((all, one, i) => {+ const ch = Math.floor(i / 2);+ all[ch] = [].concat((all[ch] || []), one);+ return all;+ }, []);++ expect(Object.fromEntries(entries)).toMatchObject({+ Accept: 'foo',+ Bar: 'BAZ',+ });});test('correctly handles invalid header characters', async () => {