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
Implement, add tests
Ondra Urban3eb34b0b29b5
diff --git a/src/cheerio_crawler.js b/src/cheerio_crawler.jsindex 012f61c80..1bc099929 100644--- a/src/cheerio_crawler.js+++ b/src/cheerio_crawler.js@@ -1,4 +1,5 @@import util from 'util';+import zlib from 'zlib';import rqst from 'request';import _ from 'underscore';import cheerio from 'cheerio';@@ -416,7 +417,10 @@ class CheerioCrawler {const mandatoryRequestOptions = {url: request.url,method: request.method,- headers: Object.assign({}, request.headers, { Accept: 'text/html' }),+ headers: Object.assign({}, request.headers, {+ Accept: 'text/html',+ 'Accept-Encoding': 'gzip, deflate',+ }),strictSSL: !this.ignoreSslErrors,proxy: this._getProxyUrl(),};@@ -447,12 +451,25 @@ class CheerioCrawler {* Flushes the provided stream into a Buffer and transforms* it to a String using the provided encoding or utf-8 as default.*- * @param {stream.Readable} stream+ * If the stream data is compressed, decompresses it using+ * the Content-Encoding header.+ *+ * @param {http.IncomingMessage} response* @param {String} [encoding]* @returns {Promise<String>}* @private*/- async _readStreamIntoString(stream, encoding) { // eslint-disable-line class-methods-use-this+ async _readStreamIntoString(response, encoding) { // eslint-disable-line class-methods-use-this+ const compression = response.headers['content-encoding'];+ let stream = response;+ if (compression) {+ 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}`);+ stream = response.pipe(decompressor);+ }+return new Promise((resolve, reject) => {const chunks = [];streamdiff --git a/src/index.js b/src/index.jsindex a40c8efdd..f81fb4fab 100644--- a/src/index.js+++ b/src/index.js@@ -1,3 +1,4 @@+import EventEmitter from 'events';import log from 'apify-shared/log';import { ENV_VARS } from 'apify-shared/consts';import { main, getEnv, call, callTask, getApifyProxyUrl } from './actor';@@ -22,6 +23,9 @@ import PseudoUrl from './pseudo_url';/* globals module */+// Increase the global limit for event emitter memory leak warnings.+EventEmitter.defaultMaxListeners = 50;+// Log as plain text not JSONlog.logJson = false;diff --git a/test/cheerio_crawler.js b/test/cheerio_crawler.jsindex c21e7c7a5..7c833bda4 100644--- a/test/cheerio_crawler.js+++ b/test/cheerio_crawler.js@@ -1,4 +1,7 @@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 chai, { expect } from 'chai';@@ -264,6 +267,156 @@ describe('CheerioCrawler', () => {});});+ describe('should handle compressed payloads', () => {+ let requestList;+ const originalGet = rqst.get;+ beforeEach(async () => {+ log.setLevel(log.LEVELS.OFF);+ 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(() => {+ log.setLevel(log.LEVELS.ERROR);+ requestList = null;+ rqst.get = originalGet;+ });++ it('by setting a correct Accept-Encoding header', async () => {+ const headers = [];+ const crawler = new Apify.CheerioCrawler({+ requestList,+ handlePageFunction: async () => {},+ requestFunction: async ({ request }) => {+ const opts = crawler._getRequestOptions(request);+ headers.push(opts.headers);+ // it needs to return something valid+ return 'html';+ },+ });++ 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',+ };++ 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',+ };++ 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 () => {+ 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': 'compress',+ };++ 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('compress');+ });+ });+ });+describe('should ensure text/html Content-Type', () => {let requestList;beforeEach(async () => {diff --git a/test/data/sample.html b/test/data/sample.htmlnew file mode 100644index 000000000..901062e83--- /dev/null+++ b/test/data/sample.html@@ -0,0 +1,20 @@+<html>+<head>+ <title>Example</title>+</head>+<body>+<p>+ The ships hung in the sky, much the <a class="click" href="https://example.com/a/b/first">way that</a> bricks don't.+</p>+<ul>+ <li>These aren't the Droids you're looking for</li>+ <li><a href="https://example.com/a/second">I'm sorry, Dave. I'm afraid I can't do that.</a></li>+ <li><a class="click" href="https://example.com/a/b/third">I'm sorry, Dave. I'm afraid I can't do that.</a></li>+</ul>+<a class="click" href="https://another.com/a/fifth">The Greatest Science Fiction Quotes Of All Time</a>+<p>+ Don't know, I don't know such stuff. I just do eyes, ju-, ju-, just eyes... just genetic design,+ just eyes. You Nexus, huh? I design your <a class="click" href="http://cool.com/">eyes</a>.+</p>+</body>+</html>