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
Refactored cheerioCrawler to use requestAsBrowser. Lowered eslint to v5
Petr Patekf38a0411b001
diff --git a/package.json b/package.jsonindex 12481ec47..963d147ee 100644--- a/package.json+++ b/package.json@@ -50,7 +50,7 @@"lint:fix": "./node_modules/.bin/eslint ./src ./test --ext .js,.jsx --fix"},"dependencies": {- "@apify/http-request": "^1.0.1",+ "@apify/http-request": "^1.0.3","@apify/ps-tree": "^1.1.3","apify-client": "^0.5.22","apify-shared": "^0.1.55",@@ -84,7 +84,7 @@"chai": "^4.2.0","chai-as-promised": "^7.1.1","chai-subset": "^1.6.0",- "eslint": "^6.1.0",+ "eslint": "^5.16.0","fpcollect": "^1.0.4","fpscanner": "^0.1.5","jsdoc": "^3.5.5",diff --git a/src/crawlers/cheerio_crawler.js b/src/crawlers/cheerio_crawler.jsindex 4aafe3609..84be8147a 100644--- a/src/crawlers/cheerio_crawler.js+++ b/src/crawlers/cheerio_crawler.js@@ -1,14 +1,11 @@/* eslint-disable class-methods-use-this */-import util from 'util';-import zlib from 'zlib';-import rqst from 'request';import _ from 'underscore';import cheerio from 'cheerio';-import contentType from 'content-type';import htmlparser from 'htmlparser2';import log from 'apify-shared/log';import { checkParamOrThrow } from 'apify-client/build/utils';+import { requestAsBrowser } from '../utils_request';import BasicCrawler from './basic_crawler';import { addTimeoutToPromise } from '../utils';import { getApifyProxyUrl } from '../actor';@@ -306,8 +303,6 @@ class CheerioCrawler {autoscaledPoolOptions,});- // See the _suppressTunnelAgentAssertError function.- this.tunnelAgentExceptionListener = null;this.isRunningPromise = null;}@@ -319,11 +314,8 @@ class CheerioCrawler {async run() {if (this.isRunningPromise) return this.isRunningPromise;- this._suppressTunnelAgentAssertError();this.isRunningPromise = this.basicCrawler.run();await this.isRunningPromise;- process.removeListener('uncaughtException', this.tunnelAgentExceptionListener);- this.tunnelAgentExceptionListener = null;}/**@@ -339,7 +331,7 @@ class CheerioCrawler {'CheerioCrawler: requestFunction timed out.',);- request.loadedUrl = response.request.uri.href;+ request.loadedUrl = response.request.gotOptions.href;const $ = cheerio.load(dom);const context = {@@ -367,75 +359,13 @@ class CheerioCrawler {* @ignore*/async _requestFunction({ request }) {- return new Promise((resolve, reject) => {- // Using the streaming API of Request to be able to- // handle the response based on headers receieved.- const opts = this._getRequestOptions(request);- const method = opts.method.toLowerCase();- rqst[method](opts)- .on('error', err => reject(err))- .on('response', async (response) => {- // First check what kind of response we received.- let cType;- try {- cType = contentType.parse(response);- } catch (err) {- response.destroy();- // No reason to parse the body if the Content-Type header is invalid.- return reject(new Error(`CheerioCrawler: Invalid Content-Type header for URL: ${request.url}`));- }-- const { type, encoding } = cType;-- // 500 codes are handled as errors, requests will be retried.- const status = response.statusCode;- if (status >= 500) {- let body;- try {- body = await this._stringifyResponseBody(this._decompressResponse(response), encoding);- } catch (err) {- // Error in reading the body.- return reject(err);- }- // Errors are often sent as JSON, so attempt to parse them,- // despite Accept header being set to text/html.- if (type === 'application/json') {- const errorResponse = JSON.parse(body);- let { message } = errorResponse;- if (!message) message = util.inspect(errorResponse, { depth: 1, maxArrayLength: 10 });- return reject(new Error(`${status} - ${message}`));- }- // It's not a JSON so it's probably some text. Get the first 100 chars of it.- return reject(new Error(`CheerioCrawler: ${status} - Internal Server Error: ${body.substr(0, 100)}`));- }+ const opts = this._getRequestOptions(request);- // Handle situations where the server explicitly states that- // it will not serve the resource as text/html by skipping.- if (status === 406) {- request.noRetry = true;- response.destroy();- return reject(new Error(`CheerioCrawler: Resource ${request.url} is not available in HTML format. Skipping resource.`));- }+ const response = await requestAsBrowser(opts);- // Other 200-499 responses are considered OK, but first check the content type.- if (type !== 'text/html') {- request.noRetry = true;- response.destroy();- return reject(new Error(- `CheerioCrawler: Resource ${request.url} served Content-Type ${type} instead of text/html. Skipping resource.`,- ));- }-- // Content-Type is fine. Read the body and respond.- try {- const dom = await this._parseHtmlToDom(this._decompressResponse(response));- resolve({ dom, response });- } catch (err) {- // Error in reading the body.- reject(err);- }- });- });+ // Content-Type is fine. Read the body and respond.+ const dom = await this._parseHtmlToDom(response);+ return { dom, response };}/**@@ -447,12 +377,8 @@ class CheerioCrawler {const mandatoryRequestOptions = {url: request.url,method: request.method,- headers: Object.assign({}, request.headers, {- Accept: 'text/html',- 'Accept-Encoding': 'gzip, deflate',- }),strictSSL: !this.ignoreSslErrors,- proxy: this._getProxyUrl(),+ proxyUrl: this._getProxyUrl(),};if (/PATCH|POST|PUT/.test(request.method)) mandatoryRequestOptions.body = request.payload;@@ -509,61 +435,10 @@ class CheerioCrawler {else resolve(dom);});const parser = new htmlparser.Parser(domHandler, { decodeEntities: true });- response.on('error', reject).pipe(parser);+ parser.write(response.body);+ parser.done();});}-- /**- * If the stream data is compressed, decompresses it using- * the Content-Encoding header.- *- * @param {http.IncomingMessage} response- * @return {http.IncomingMessage}- * @private- */- _decompressResponse(response) {- const compression = response.headers['content-encoding'];- if (!compression) return response;- let decompressor;- if (compression === 'gzip') decompressor = zlib.createGunzip();- else if (compression === 'deflate') decompressor = zlib.createInflate();- else throw new Error(`CheerioCrawler: Invalid Content-Encoding header. Expected gzip or deflate, but received: ${compression}`);- return response.pipe(decompressor);- }-- /**- * The handler this function attaches overcomes a long standing bug in- * the tunnel-agent NPM package that is used by the Request package internally.- * The package throws an assertion error in a callback scope that cannot be- * caught by conventional means and shuts down the running process.- * @ignore- */- _suppressTunnelAgentAssertError() {- // Only set the handler if it's not already set.- if (this.tunnelAgentExceptionListener) return;- this.tunnelAgentExceptionListener = (err) => {- try {- const code = err.code === 'ERR_ASSERTION';- const name = err.name === 'AssertionError [ERR_ASSERTION]';- const operator = err.operator === '==';- const value = err.expected === 0;- const stack = err.stack.includes('/tunnel-agent/index.js');- // If this passes, we can be reasonably sure that it's- // the right error from tunnel-agent.- if (code && name && operator && value && stack) {- log.error('CheerioCrawler: Tunnel-Agent assertion error intercepted. The affected request will timeout.');- return;- }- } catch (caughtError) {- // Catch any exception resulting from the duck-typing- // check. It only means that the error is not the one- // we're looking for.- }- // Rethrow the original error if it's not a match.- throw err;- };- process.on('uncaughtException', this.tunnelAgentExceptionListener);- }}export default CheerioCrawler;diff --git a/src/utils_request.js b/src/utils_request.jsindex 232be7b59..882f4b762 100644--- a/src/utils_request.js+++ b/src/utils_request.js@@ -19,6 +19,7 @@ export const REQUEST_AS_BROWSER_DEFAULT_OPTIONS = {return res.statusCode === 406 || type.toLowerCase() !== 'text/html';},useCaseSensitiveHeaders: true,+ stream: false,};/*** Sends a HTTP request that looks like a request sent by a web browser,@@ -58,11 +59,11 @@ export const REQUEST_AS_BROWSER_DEFAULT_OPTIONS = {* If function returns true request gets aborted. This function is passed to the* (@apify/http-request)[https://www.npmjs.com/package/@apify/http-request] NPM package.*- * @return {http.IncomingMessage}+ * @return {Promise}* @memberOf utils* @name requestAsBrowser*/-export const requestAsBrowser = async (options) => {+export const requestAsBrowser = (options) => {const opts = _.defaults({}, options, REQUEST_AS_BROWSER_DEFAULT_OPTIONS);const parsedUrl = url.parse(opts.url);diff --git a/test/crawlers/cheerio_crawler.js b/test/crawlers/cheerio_crawler.jsindex 1610f38c7..300363a26 100644--- a/test/crawlers/cheerio_crawler.js+++ b/test/crawlers/cheerio_crawler.js@@ -1,9 +1,3 @@-import { Readable } from 'stream';-import fs from 'fs';-import path from 'path';-import zlib from 'zlib';-import EventEmitter from 'events';-import rqst from 'request';import { expect } from 'chai';import log from 'apify-shared/log';import { delayPromise } from 'apify-shared/utilities';@@ -13,7 +7,7 @@ import Apify from '../../build';// Add common props to mocked request responses.const responseMock = {request: {- uri: {+ gotOptions: {href: 'loadedUrl',},},@@ -40,12 +34,12 @@ describe('CheerioCrawler', () => {it('should work', async () => {const sources = [- { url: 'http://example.com/?q=1' },- { url: 'http://example.com/?q=2' },- { url: 'http://example.com/?q=3' },- { url: 'http://example.com/?q=4' },- { url: 'http://example.com/?q=5' },- { url: 'http://example.com/?q=6' },+ { url: 'http://www.example.com/?q=1' },+ { url: 'http://www.example.com/?q=2' },+ { url: 'http://www.example.com/?q=3' },+ { url: 'http://www.example.com/?q=4' },+ { url: 'http://www.example.com/?q=5' },+ { url: 'http://www.example.com/?q=6' },];const processed = [];const failed = [];@@ -66,7 +60,6 @@ describe('CheerioCrawler', () => {await requestList.initialize();await cheerioCrawler.run();-expect(processed).to.have.lengthOf(6);expect(failed).to.have.lengthOf(0);@@ -200,455 +193,6 @@ describe('CheerioCrawler', () => {});});- describe('should handle compressed payloads', () => {- let requestList;- const originalGet = rqst.get;- beforeEach(async () => {- requestList = new Apify.RequestList({- sources: [- { url: 'http://example.com/?q=0' },- { url: 'http://example.com/?q=1' },- { url: 'http://example.com/?q=2' },- { url: 'http://example.com/?q=3' },- ],- });- await requestList.initialize();- });-- afterEach(() => {- requestList = null;- rqst.get = originalGet;- });-- it('by setting a correct Accept-Encoding header', async () => {- const headers = [];- const crawler = new Apify.CheerioCrawler({- requestList,- handlePageFunction: async () => {},- });-- crawler._requestFunction = async ({ request }) => {- const opts = crawler._getRequestOptions(request);- headers.push(opts.headers);- // it needs to return something valid- return { dom: {}, response: responseMock };- };-- await crawler.run();- headers.forEach(h => expect(h['Accept-Encoding']).to.be.eql('gzip, deflate'));- });-- it('by decompressing a gzip compressed response', async () => {- const sourceFilePath = path.join(__dirname, 'data', 'sample.html');- const allHTML = [];- const crawler = new Apify.CheerioCrawler({- requestList,- handlePageFunction: async ({ html }) => {- allHTML.push(html);- },- });- // Mock Request to inject a gzipped stream.- rqst.get = () => {- const response = fs.createReadStream(sourceFilePath).pipe(zlib.createGzip());- response.headers = {- 'content-type': 'text/html', // to avoid throwing- 'content-encoding': 'gzip',- };- Object.assign(response, responseMock);-- const ee = new EventEmitter();-- setTimeout(() => {- ee.emit('response', response);- }, 0);-- return ee;- };-- await crawler.run();-- const rawHtml = fs.readFileSync(sourceFilePath, 'utf8');- expect(allHTML).to.have.lengthOf(4);- allHTML.forEach((html) => {- expect(html).to.be.eql(rawHtml);- });- });-- it('by decompressing a deflate compressed response', async () => {- const sourceFilePath = path.join(__dirname, 'data', 'sample.html');- const allHTML = [];- const crawler = new Apify.CheerioCrawler({- requestList,- handlePageFunction: async ({ html }) => {- allHTML.push(html);- },- });- // Mock Request to inject a gzipped stream.- rqst.get = () => {- const response = fs.createReadStream(sourceFilePath).pipe(zlib.createDeflate());- response.headers = {- 'content-type': 'text/html', // to avoid throwing- 'content-encoding': 'deflate',- };- Object.assign(response, responseMock);-- const ee = new EventEmitter();-- setTimeout(() => {- ee.emit('response', response);- }, 0);-- return ee;- };-- await crawler.run();-- const rawHtml = fs.readFileSync(sourceFilePath, 'utf8');- expect(allHTML).to.have.lengthOf(4);- allHTML.forEach((html) => {- expect(html).to.be.eql(rawHtml);- });- });-- it('by throwing on unsupported Content-Encoding', async () => {- log.setLevel(log.LEVELS.OFF);- const sourceFilePath = path.join(__dirname, 'data', 'sample.html');- let handlePageInvocationCount = 0;- let allErrors = [];- const crawler = new Apify.CheerioCrawler({- requestList,- handlePageFunction: async () => {- handlePageInvocationCount++;- },- handleFailedRequestFunction: async ({ request }) => {- allErrors = allErrors.concat(request.errorMessages);- },- });- // Mock Request to inject a gzipped stream.- rqst.get = () => {- const response = fs.createReadStream(sourceFilePath);- response.headers = {- 'content-type': 'text/html', // to avoid throwing- 'content-encoding': 'bad-encoding',- };- Object.assign(response, responseMock);-- const ee = new EventEmitter();-- setTimeout(() => {- ee.emit('response', response);- }, 0);-- return ee;- };-- await crawler.run();-- expect(allErrors).to.have.lengthOf(16);- expect(handlePageInvocationCount).to.be.eql(0);- allErrors.forEach((err) => {- expect(err).to.include('Invalid Content-Encoding header');- expect(err).to.include('bad-encoding');- });- log.setLevel(log.LEVELS.ERROR);- });- });-- describe('should ensure text/html Content-Type', () => {- let requestList;- beforeEach(async () => {- requestList = new Apify.RequestList({- sources: [- { url: 'http://example.com/?q=0' },- { url: 'http://example.com/?q=1' },- { url: 'http://example.com/?q=2' },- { url: 'http://example.com/?q=3' },- ],- });- await requestList.initialize();- });-- afterEach(() => {- requestList = null;- });-- it('by setting a correct Accept header', async () => {- const headers = [];- const crawler = new Apify.CheerioCrawler({- requestList,- handlePageFunction: async () => {},- });-- crawler._requestFunction = async ({ request }) => {- const opts = crawler._getRequestOptions(request);- headers.push(opts.headers);- // it needs to return something valid- return { dom: {}, response: responseMock };- };-- await crawler.run();- headers.forEach(h => expect(h.Accept).to.be.eql('text/html'));- });-- describe('by throwing', () => {- let crawler;- let originalGet;- let handlePageInvocationCount = 0;- let errorMessages = [];- let chunkReadCount = 0;- const getChunk = (chunk = 'x') => {- chunkReadCount++;- return chunk;- };-- before(() => {- originalGet = rqst.get;- });-- after(() => {- rqst.get = originalGet;- });-- beforeEach(() => {- log.setLevel(log.LEVELS.OFF);- crawler = new Apify.CheerioCrawler({- requestList,- maxRequestRetries: 1,- handlePageFunction: async () => {- handlePageInvocationCount++;- },- handleFailedRequestFunction: async ({ request }) => {- errorMessages = [...errorMessages, ...request.errorMessages];- },- });- });- afterEach(async () => {- log.setLevel(log.LEVELS.ERROR);- crawler = null;- handlePageInvocationCount = 0;- chunkReadCount = 0;- errorMessages = [];- });--- it('when invalid Content-Type header is received', async () => {- // Mock Request to inject invalid response headers.- rqst.get = () => {- const response = new Readable({- read() {- this.push(getChunk());- this.push(null);- },- });- response.headers = {- 'content-type': '000',- };-- const ee = new EventEmitter();-- setTimeout(() => {- ee.emit('response', response);- }, 0);-- return ee;- };-- await crawler.run();-- expect(handlePageInvocationCount).to.be.eql(0);- expect(errorMessages).to.have.lengthOf(8);- errorMessages.forEach(msg => expect(msg).to.include('Invalid Content-Type header'));- expect(chunkReadCount).to.be.eql(0);- });-- it('when response stream emits an error event', async () => {- // Mock Request to emit an error after a while.- rqst.get = () => {- const start = Date.now();- const response = new Readable({- read() {- if (Date.now() > start + 1) {- this.emit('error', new Error('Error in stream.'));- return;- }- this.push(getChunk());- },- });- response.headers = {- 'content-type': 'text/html',- };-- const ee = new EventEmitter();-- setTimeout(() => {- ee.emit('response', response);- }, 0);-- return ee;- };-- await crawler.run();-- expect(handlePageInvocationCount).to.be.eql(0);- expect(errorMessages).to.have.lengthOf(8);- errorMessages.forEach(msg => expect(msg).to.include('Error in stream.'));- });-- it('when request stream emits an error event', async () => {- // Mock Request to emit an error after a while.- rqst.get = () => {- const response = new Readable({- // Just do nothing- read() {},- });- response.headers = {- 'content-type': 'text/html',- };-- const ee = new EventEmitter();-- setTimeout(() => {- ee.emit('response', response);- setTimeout(() => {- ee.emit('error', new Error('Request Error.'));- }, 0);- }, 0);-- return ee;- };-- await crawler.run();-- expect(handlePageInvocationCount).to.be.eql(0);- expect(errorMessages).to.have.lengthOf(8);- errorMessages.forEach(msg => expect(msg).to.include('Request Error.'));- });-- it('when statusCode >= 500 and text/html is received', async () => {- rqst.get = () => {- const response = new Readable({- read() {- this.push(getChunk());- this.push(null);- },- });- response.headers = {- 'content-type': 'text/html',- };- response.statusCode = 500;-- const ee = new EventEmitter();-- setTimeout(() => {- ee.emit('response', response);- }, 0);-- return ee;- };-- await crawler.run();-- expect(handlePageInvocationCount).to.be.eql(0);- expect(errorMessages).to.have.lengthOf(8);- errorMessages.forEach(msg => expect(msg).to.include('Internal Server Error: x'));- expect(chunkReadCount).to.be.eql(8);- });-- it('when statusCode >= 500 and application/json is received', async () => {- rqst.get = () => {- const response = new Readable({- // Just do nothing- read() {- this.push(getChunk(JSON.stringify({ message: 'Hello' })));- this.push(null);- },- });- response.headers = {- 'content-type': 'application/json',- };- response.statusCode = 500;-- const ee = new EventEmitter();-- setTimeout(() => {- ee.emit('response', response);- }, 0);-- return ee;- };-- await crawler.run();-- expect(handlePageInvocationCount).to.be.eql(0);- expect(errorMessages).to.have.lengthOf(8);- errorMessages.forEach(msg => expect(msg).to.include('500 - Hello'));- expect(chunkReadCount).to.be.eql(8);- });-- it('when 406 is received', async () => {- // Mock Request to respond with a 406.- rqst.get = () => {- const response = new Readable({- read() {- this.push(getChunk());- this.push(null);- },- });- response.headers = {- 'content-type': 'text/plain',- };- response.statusCode = 406;-- const ee = new EventEmitter();-- setTimeout(() => {- ee.emit('response', response);- }, 0);-- return ee;- };-- await crawler.run();-- expect(handlePageInvocationCount).to.be.eql(0);- expect(errorMessages).to.have.lengthOf(4);- errorMessages.forEach(msg => expect(msg).to.include('is not available in HTML format'));- expect(chunkReadCount).to.be.eql(0);- });-- it('when status is ok, but a wrong content type is received', async () => {- // Mock Request to respond with a 406.- rqst.get = () => {- const response = new Readable({- read() {- this.push(getChunk());- this.push(null);- },- });- response.headers = {- 'content-type': 'application/json',- };- response.statusCode = 200;-- const ee = new EventEmitter();-- setTimeout(() => {- ee.emit('response', response);- }, 0);-- return ee;- };-- await crawler.run();-- expect(handlePageInvocationCount).to.be.eql(0);- expect(errorMessages).to.have.lengthOf(4);- errorMessages.forEach(msg => expect(msg).to.include('served Content-Type application/json instead of text/html'));- expect(chunkReadCount).to.be.eql(0);- });- });- });-describe('proxy', () => {let requestList;beforeEach(async () => {@@ -677,7 +221,7 @@ describe('CheerioCrawler', () => {crawler._requestFunction = async ({ request }) => {const opts = crawler._getRequestOptions(request);- proxies.push(opts.proxy);+ proxies.push(opts.proxyUrl);// it needs to return something validreturn { dom: {}, response: responseMock };};@@ -707,7 +251,7 @@ describe('CheerioCrawler', () => {crawler._requestFunction = async ({ request }) => {const opts = crawler._getRequestOptions(request);- proxies.push(opts.proxy);+ proxies.push(opts.proxyUrl);// it needs to return something validreturn { dom: {}, response: responseMock };};@@ -744,7 +288,7 @@ describe('CheerioCrawler', () => {crawler._requestFunction = async ({ request }) => {const opts = crawler._getRequestOptions(request);- proxies.push(opts.proxy);+ proxies.push(opts.proxyUrl);// it needs to return something validreturn { dom: {}, response: responseMock };};@@ -796,71 +340,4 @@ describe('CheerioCrawler', () => {});});});-- // It would make sense to also test that the listener does not prevent other- // uncaught exceptions from exiting the process, but since the exceptions- // thrown from within the listener cannot be caught anymore, there's no way- // to do this, because the re-thrown error will always crash the test process.- describe('tunnel-agent error handler', () => {- const throwNextTick = (err) => {- process.nextTick(() => {- throw err;- });- };-- let mochaListener;-- before(() => {- log.setLevel(log.LEVELS.OFF);- mochaListener = process.listeners('uncaughtException').shift();- process.removeListener('uncaughtException', mochaListener);- });- after(() => {- log.setLevel(log.LEVELS.ERROR);- process.on('uncaughtException', mochaListener);- });-- it('should suppress tunnel-agent errors', async () => {- let handlePageCalled = false;- let handleFailedRequestCallCount = 0;-- const requestList = new Apify.RequestList({- sources: [- { url: 'http://example.com/?q=0' },- { url: 'http://example.com/?q=1' },- { url: 'http://example.com/?q=2' },- { url: 'http://example.com/?q=3' },- ],- });-- const crawler = new Apify.CheerioCrawler({- requestList,- requestTimeoutSecs: 1 / 1000,- handlePageFunction: () => {- handlePageCalled = true;- },- handleFailedRequestFunction: () => {- handleFailedRequestCallCount++;- },- });-- crawler._requestFunction = async () => {- const err = new Error();- err.code = 'ERR_ASSERTION';- err.name = 'AssertionError [ERR_ASSERTION]';- err.operator = '==';- err.expected = 0;- err.stack = ('xxx/tunnel-agent/index.js/yyyy');- throwNextTick(err);- // will never resolve- await new Promise(() => {});- };-- await requestList.initialize();- await crawler.run();-- expect(handlePageCalled).to.be.eql(false);- expect(handleFailedRequestCallCount).to.be.eql(4);- });- });});