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.

Added new Apify.utils.htmlToText() function to improve Apify.utils.social.parseHandlesFromHtml()

Jan Curn4c0e5e3e7377
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f3daa0538..a67d89fa6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,8 @@
+xxx
+===================
+- Added `Apify.utils.htmlToText()` function to convert HTML to text and removed unncessary `html-to-text` dependency.
+ The new function is now used in `Apify.utils.social.parseHandlesFromHtml()`.
+
0.10.0 / 2018-12-19
===================
- `autoscaledPool.isFinishedFunction()` and `autoscaledPool.isTaskReadyFunction()` exceptions
diff --git a/package.json b/package.json
index b66352053..7a0184389 100644
--- a/package.json
+++ b/package.json
@@ -56,7 +56,6 @@
"cheerio": "^1.0.0-rc.2",
"content-type": "^1.0.4",
"fs-extra": "^7.0.1",
- "html-to-text": "^4.0.0",
"jquery": "^3.3.1",
"mime": "^2.3.1",
"proxy-chain": "^0.2.5",
diff --git a/src/utils.js b/src/utils.js
index 8728eb137..f9fac2979 100644
--- a/src/utils.js
+++ b/src/utils.js
@@ -7,11 +7,11 @@ import ApifyClient from 'apify-client';
import psTree from '@apify/ps-tree';
import requestPromise from 'request-promise-native';
import XRegExp from 'xregexp';
+import cheerio from 'cheerio';
import { delayPromise, getRandomInt } from 'apify-shared/utilities';
import { ENV_VARS, LOCAL_ENV_VARS } from 'apify-shared/consts';
import { checkParamOrThrow } from 'apify-client/build/utils';
import { USER_AGENT_LIST } from './constants';
-import cheerio from 'cheerio';
/* globals process */
@@ -483,65 +483,79 @@ export const ensureTokenOrLocalStorageEnvExists = (storageName) => {
};
+const SKIP_TAGS_REGEX = /^(script|style|canvas|svg)$/i;
+const BLOCK_TAGS_REGEX = /^(p|h1|h2|h3|h4|h5|h6|ol|ul|li|pre|address|blockquote|dl|div|fieldset|form|noscript|table|tr)$/i;
+
/**
- * The function converts a HTML document to plain text.
+ * The function converts a HTML document to a plain text.
+ *
+ * The plain text generated by the function is similar to a text captured
+ * by pressing Ctrl+A and Ctrl+C on a page when loaded in a web browser.
+ * The function doesn't aspire to preserve the formatting or to be perfectly correct with respect to HTML specifications.
+ * However, it attempts to generate newlines and whitespaces in and around HTML elements
+ * to avoid merging distinct parts of text and thus enable extraction of data from the text (e.g. phone numbers).
+ *
+ * **Example usage**
+ * ```javascript
+ * const text = htmlToText('<html><body>Some text</body></html>');
+ * console.log(text);
+ * ```
*
- * Unlike packages like https://www.npmjs.com/package/html-to-text, the function doesn't attempt to preserve any formatting,
- * but it makes best effort to correctly place newlines and spaces in the text, so that words are correctly separated
- * in order to enable extraction of data from the text (e.g. phone numbers).
- * @param html
- * @return {*}
+ * Note that the function uses [cheerio](https://www.npmjs.com/package/cheerio) to parse the HTML.
+ * Optionally, to avoid duplicate parsing of HTML and thus improve performance, you can pass
+ * an existing Cheerio object to the function instead of the HTML text. The HTML should be parsed
+ * with the `decodeEntities` option set to `true`. For example:
+ *
+ * ```javascript
+ * const cheerio = require('cheerio');
+ * const html = '<html><body>Some text</body></html>';
+ * const text = htmlToText(cheerio.load(html, { decodeEntities: true }));
+ * ```
+ * @param {String|Function} html HTML text or parsed HTML represented using a
+ * [cheerio](https://www.npmjs.com/package/cheerio) function.
+ * @return {String} Plain text
*/
export const htmlToText = (html) => {
- const $ = cheerio.load(html, { decodeEntities: true });
-
- // Remove these elements
- $('script, style, svg, canvas, img').remove();
-
- // Remove HTML comments
- const $comments = $('*').contents().filter(function () {
- return this.nodeType === 8;
- });
- $comments.each(function () {
- $(this).remove();
- });
-
- // Remove attributes
- $('*').each(function (index, elem) {
- const $elem = $(elem);
- for (const name in this.attribs) {
- $elem.removeAttr(name);
+ if (!html) return '';
+
+ const $ = typeof html === 'function' ? html : cheerio.load(html, { decodeEntities: true });
+ let text = '';
+
+ const process = (elems) => {
+ const len = elems.length;
+ for (let i = 0; i < len; i++) {
+ const elem = elems[i];
+ if (elem.type === 'text') {
+ // Compress spaces, unless we're inside <pre> element
+ let compr;
+ if (elem.parent && elem.parent.tagName === 'pre') compr = elem.data;
+ else compr = elem.data.replace(/\s+/g, ' ');
+ // If text is empty or ends with a whitespace, don't add the leading whitepsace
+ if (compr.startsWith(' ') && /(^|\s)$/.test(text)) compr = compr.substr(1);
+ text += compr;
+ } else if (elem.type === 'comment' || SKIP_TAGS_REGEX.test(elem.tagName)) {
+ // Skip comments and special elements
+ } else if (elem.tagName === 'br') {
+ text += '\n';
+ } else if (elem.tagName === 'td') {
+ process(elem.children);
+ text += '\t';
+ } else {
+ // Block elements must be surrounded by newlines (unless beginning of text)
+ const isBlockTag = BLOCK_TAGS_REGEX.test(elem.tagName);
+ if (isBlockTag && !/(^|\n)$/.test(text)) text += '\n';
+ process(elem.children);
+ if (isBlockTag && !text.endsWith('\n')) text += '\n';
+ }
}
- });
-
- let html = return $('body').html();
-
- return html;
-
- // Now, convert various HTML tags to text
- // html.replace('<br>')
-
-
- /*
-
-
- const handler = new htmlparser.DomHandler((error, dom) => {}, { verbose: true });
-
- new htmlparser.Parser(handler).parseComplete(html);
+ };
- var result = '';
- var baseElements = Array.isArray(options.baseElement) ? options.baseElement : [options.baseElement];
- for (var idx = 0; idx < baseElements.length; ++idx) {
- result += walk(filterBody(handler.dom, options, baseElements[idx]), options);
- }
- if (options.collapseNewlines) {
- result = result.trim().replace(/\r/g, '').replace(/\n+/g, '\n');
- }
- return trimEnd(result);
-*/
+ // If HTML document has body, only convert that, otherwise convert the entire HTML
+ const $body = $('body');
+ process($body.length > 0 ? $body : $.root());
- return html;
+ return text.trim();
};
diff --git a/src/utils_social.js b/src/utils_social.js
index e0d8a10e3..911d8f83d 100644
--- a/src/utils_social.js
+++ b/src/utils_social.js
@@ -1,6 +1,5 @@
/* eslint-disable no-continue */
import _ from 'underscore';
-import htmlToText from 'html-to-text';
import cheerio from 'cheerio';
import log from 'apify-shared/log';
@@ -487,15 +486,14 @@ const parseHandlesFromHtml = (html, data = null) => {
if (!_.isString(html)) return result;
+ const $ = cheerio.load(html, { decodeEntities: true });
+ if (data) data.$ = $;
+
// We use ignoreHref and ignoreImage options so that the text doesn't contain links,
// since their parts can be interpreted as e.g. phone numbers.
- const text = htmlToText.fromString(html, { ignoreHref: true, ignoreImage: true }) || '';
+ const text = Apify.utils.htmlToText($);
if (data) data.text = text;
- // TODO: Both html-to-text and cheerio use htmlparser2, the parsing could be done only once to improve performance
- const $ = cheerio.load(html, { decodeEntities: true });
- if (data) data.$ = $;
-
// Find all <a> links with href tag
const linkUrls = [];
$('a[href]').each((index, elem) => {
diff --git a/test/utils.js b/test/utils.js
index a20982c32..0b77d010c 100644
--- a/test/utils.js
+++ b/test/utils.js
@@ -4,6 +4,7 @@ import sinon from 'sinon';
import fs from 'fs';
import path from 'path';
import os from 'os';
+import cheerio from 'cheerio';
import requestPromise from 'request-promise-native';
import LruCache from 'apify-shared/lru_cache';
import { ENV_VARS, LOCAL_ENV_VARS } from 'apify-shared/consts';
@@ -14,17 +15,6 @@ chai.use(chaiAsPromised);
/* global process, describe, it */
-describe('utils.htmlToText()', () => {
-
- it('works', () => {
- const html = fs.readFileSync('/Users/jan/Projects/apify-js/test_html/prunty.html');
-
- const text = utils.htmlToText(html);
- console.log(text);
- });
-});
-
-
describe('utils.newClient()', () => {
it('reads environment variables correctly', () => {
process.env[ENV_VARS.API_BASE_URL] = 'http://www.example.com:1234/path/';
@@ -666,3 +656,105 @@ describe('utils.openRemoteStorage()', async () => {
delete process.env['some-env'];
});
});
+
+const checkHtmlToText = (html, expectedText) => {
+ const text1 = utils.htmlToText(html);
+ expect(text1).to.eql(expectedText);
+
+ // Test embedding into <body> gives the same result
+ if (typeof html === 'string') {
+ const html2 = `
+ <html>
+ <head>
+ <title>Title should be ignored</title>
+ <style>
+ .styles_should_be_ignored_too {}
+ </style>
+ <script type="application/javascript">
+ scriptsShouldBeIgnoredToo();
+ </script>
+ </head>
+ <body>
+ ${html}
+ </body>
+ </html>`;
+ const text2 = utils.htmlToText(html2);
+ expect(text2).to.eql(expectedText);
+ }
+};
+
+describe('utils.htmlToText()', () => {
+ it('handles invalid args', () => {
+ checkHtmlToText(null, '');
+ checkHtmlToText('', '');
+ checkHtmlToText(0, '');
+ checkHtmlToText(undefined, '');
+ });
+
+ it('handles basic HTML elements correctly', () => {
+ checkHtmlToText('Plain text node', 'Plain text node');
+ checkHtmlToText(' Plain text node ', 'Plain text node');
+ checkHtmlToText(' \nPlain text node \n ', 'Plain text node');
+
+ checkHtmlToText('<h1>Header 1</h1> <h2>Header 2</h2>', 'Header 1\nHeader 2');
+ checkHtmlToText('<h1>Header 1</h1> <h2>Header 2</h2><br>', 'Header 1\nHeader 2');
+ checkHtmlToText('<h1>Header 1</h1> <h2>Header 2</h2><br><br>', 'Header 1\nHeader 2');
+ checkHtmlToText('<h1>Header 1</h1> <h2>Header 2</h2><br><br><br>', 'Header 1\nHeader 2');
+
+ checkHtmlToText('<h1>Header 1</h1><br><h2>Header 2</h2><br><br><br>', 'Header 1\n\nHeader 2');
+ checkHtmlToText('<h1>Header 1</h1> <br> <h2>Header 2</h2><br><br><br>', 'Header 1\n\nHeader 2');
+ checkHtmlToText('<h1>Header 1</h1> \n <br>\n<h2>Header 2</h2><br><br><br>', 'Header 1\n\nHeader 2');
+ checkHtmlToText('<h1>Header 1</h1> \n <br>\n<br><h2>Header 2</h2><br><br><br>', 'Header 1\n\n\nHeader 2');
+ checkHtmlToText('<h1>Header 1</h1> \n <br>\n<br><br><h2>Header 2</h2><br><br><br>', 'Header 1\n\n\n\nHeader 2');
+
+ checkHtmlToText('<div><div>Div</div><p>Paragraph</p></div>', 'Div\nParagraph');
+ checkHtmlToText('<div>Div1</div><!-- Some comments --><div>Div2</div>', 'Div1\nDiv2');
+
+ checkHtmlToText('<div>Div1</div><style>Skip styles</style>', 'Div1');
+ checkHtmlToText('<script>Skip_scripts();</script><div>Div1</div>', 'Div1');
+ checkHtmlToText('<SCRIPT>Skip_scripts();</SCRIPT><div>Div1</div>', 'Div1');
+ checkHtmlToText('<svg>Skip svg</svg><div>Div1</div>', 'Div1');
+ checkHtmlToText('<canvas>Skip canvas</canvas><div>Div1</div>', 'Div1');
+
+ checkHtmlToText('<b>A B C D E\n\nF G</b>', 'A B C D E F G');
+ checkHtmlToText('<pre>A B C D E\n\nF G</pre>', 'A B C D E\n\nF G');
+
+ checkHtmlToText(
+ '<h1>Heading 1</h1><div><div><div><div>Deep Div</div></div></div></div><h2>Heading 2</h2>',
+ 'Heading 1\nDeep Div\nHeading 2',
+ );
+
+ checkHtmlToText('<a>this_word</a>_should_<b></b>be_<span>one</span>', 'this_word_should_be_one');
+ checkHtmlToText('<span attributes="should" be="ignored">some <span>text</span></span>', 'some text');
+
+ checkHtmlToText(
+ `<table>
+ <tr>
+ <td>Cell A1</td><td>Cell A2</td>
+ <td> Cell A3 </td>
+ </tr>
+ <tr>
+ <td>Cell B1</td><td>Cell B2</td>
+ </tr>
+ </table>`,
+ 'Cell A1\tCell A2\tCell A3 \t\nCell B1\tCell B2',
+ );
+ });
+
+ it('handles HTML entities correctly', () => {
+ checkHtmlToText('<span>&aacute; &eacute;</span>', 'á é');
+ });
+
+ xit('handles complex HTML document', () => {
+ // TODO: Test some longer HTML document
+ });
+
+ it('works with Cheerio object', () => {
+ const html1 = '<html><body>Some text</body></html>';
+ checkHtmlToText(cheerio.load(html1, { decodeEntities: true }), 'Some text');
+
+ const html2 = '<h1>Text outside of body</h1>';
+ checkHtmlToText(cheerio.load(html2, { decodeEntities: true }), 'Text outside of body');
+ });
+});
+