Skip to content

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.

Merge branch 'master' into feature/session-pool-cheerio

Petr Patek824e7b65213b
diff --cc src/crawlers/cheerio_crawler.js
index 62aaad45d,32bc4fc0b..cf3ac876d
--- a/src/crawlers/cheerio_crawler.js
+++ b/src/crawlers/cheerio_crawler.js
@@@ -369,21 -354,17 +371,21 @@@ class CheerioCrawler
*
* @ignore
*/
- async _handleRequestFunction({ request, autoscaledPool }) {
+ async _handleRequestFunction({ request, autoscaledPool, session }) {
- if (this.prepareRequestFunction) await this.prepareRequestFunction({ request, session });
- const { dom, isXmlOrHtml, body, contentType, responseStream: response } = await addTimeoutToPromise(
+ if (this.prepareRequestFunction) await this.prepareRequestFunction({ request });
+ const { dom, isXml, body, contentType, response } = await addTimeoutToPromise(
- this._requestFunction({ request }),
+ this._requestFunction({ request, session }),
this.requestTimeoutMillis,
`CheerioCrawler: request timed out after ${this.requestTimeoutMillis / 1000} seconds.`,
);
+ if (this.persistCookiesPerSession) {
+ session = this._updateSessionCookies(session, response);
+ }
+
request.loadedUrl = response.url;
- const $ = dom ? cheerio.load(dom, { xmlMode: isXmlOrHtml }) : null;
+ const $ = dom ? cheerio.load(dom, { xmlMode: isXml }) : null;
const context = {
$,
// Using a getter here not to break the original API
@@@ -460,14 -437,12 +465,14 @@@
// It's not a JSON so it's probably some text. Get the first 100 chars of it.
throw new Error(`CheerioCrawler: ${statusCode} - Internal Server Error: ${body.substr(0, 100)}`);
+ } else if (STATUS_CODES_BLOCKED.includes(statusCode)) {
+ this._handleBlockedRequest(session, statusCode);
} else if (type === 'text/html' || type === 'application/xhtml+xml' || type === 'application/xml') {
- const dom = await this._parseHtmlToDom(responseStream);
- return ({ dom, isXmlOrHtml: type.includes('xml'), responseStream, contentType });
+ const dom = await this._parseHtmlToDom(response);
+ return ({ dom, isXml: type.includes('xml'), response, contentType });
} else {
- const body = await concatStreamToBuffer(responseStream);
- return { body, responseStream, contentType };
+ const body = await concatStreamToBuffer(response);
+ return { body, response, contentType };
}
}
diff --cc src/utils.js
index c93b6cd46,cd12ffc25..189327c2c
--- a/src/utils.js
+++ b/src/utils.js
@@@ -664,28 -663,12 +664,31 @@@ export const parseContentTypeFromRespon
parsedContentType = contentTypeParser.parse(contentTypeFromExtname);
}
- return parsedContentType;
+ return {
+ type: parsedContentType.type,
+ charset: parsedContentType.parameters.charset,
+ };
};
+export const getCookiesFromResponse = (response) => {
+ const { headers } = response;
+ let cookies;
+
+ if (Array.isArray(headers['set-cookie'])) {
+ cookies = headers['set-cookie'].map(Cookie.parse);
+ } else {
+ cookies = [Cookie.parse(headers['set-cookie'])];
+ }
+
+ return cookies;
+};
+
+export const getCookieHeader = (cookies) => {
+ if (cookies.length < 1) {
+ return;
+ }
+ return cookies.map(cookie => cookie && cookie.cookieString()).join(';');
+};
/**
* A namespace that contains various utilities.
*
diff --cc test/utils.test.js
index f4b339e4a,465485abc..444a8db39
--- a/test/utils.test.js
+++ b/test/utils.test.js
@@@ -961,51 -959,6 +960,51 @@@ describe('utils.parseContentTypeFromRes
const parsedReallyBad = utils.parseContentTypeFromResponse({ url: 'http://www.example.com/foo', headers: { 'content-type': 'crazy-stuff' } });
expect(parsedReallyBad.type).toBe('application/octet-stream');
- expect(parsedReallyBad.parameters.charset).toBe('utf-8');
+ expect(parsedReallyBad.charset).toBe('utf-8');
});
});
+
+describe('utils.getCookiesFromResponse & utils.getCookieHeader', () => {
+ test('should parse cookies if set-cookie is array', () => {
+ const headers = {};
+ const dummyCookies = ['CSRF=e8b667; Domain=example.com; Secure', 'id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT'];
+ headers['set-cookie'] = dummyCookies;
+ const cookies = utils.getCookiesFromResponse({ headers });
+
+ cookies.forEach((cookie) => {
+ expect(cookie).toBeInstanceOf(Cookie);
+ });
+
+ expect(dummyCookies[0]).toEqual(cookies[0].toString());
+ expect(dummyCookies[1]).toEqual(cookies[1].toString());
+
+ const parsed = utils.getCookieHeader(cookies);
+ expect(parsed).toEqual('CSRF=e8b667;id=a3fWa');
+ });
+
+ test('should parse cookies if set-cookie is string', () => {
+ const headers = {};
+ const dummyCookie = 'CSRF=e8b667; Domain=example.com; Secure';
+ headers['set-cookie'] = dummyCookie;
+ const cookies = utils.getCookiesFromResponse({ headers });
+
+ expect(cookies).toHaveLength(1);
+ expect(dummyCookie).toEqual(cookies[0].toString());
+ expect(cookies[0]).toBeInstanceOf(Cookie);
+ const parsed = utils.getCookieHeader(cookies);
+ expect(parsed).toEqual('CSRF=e8b667');
+ });
+
+ test('should not throw error on parsing invalid cookie', () => {
+ const headers = {};
+ const dummyCookie = 'totally Invalid Cookie $@$@#$**';
+ headers['set-cookie'] = dummyCookie;
+ const cookies = utils.getCookiesFromResponse({ headers });
+
+ expect(cookies).toHaveLength(1);
+ expect(cookies[0]).toBeUndefined();
+
+ const parsed = utils.getCookieHeader(cookies);
+ expect(parsed).toBeFalsy();
+ });
+});