Extracting Text from HTML in Perl: What Survives the Conversion

A practical review of Perl HTML-to-text conversion: what the conversion changes, what it loses, how links and encoding behave, and when plain output is the right choice.

Converting HTML to plain text in Perl is a common step before indexing, emailing, diffing or feeding page content into another tool. This review covers what the conversion changes, what it discards and when the output is good enough for the job. It relies on the documented behavior of widely used CPAN modules and on general principles of HTML. No benchmarks or test results were supplied for this review, so none are reported here.

Is HTML-to-text conversion suitable for your use?

The conversion suits tasks that need the words of a page and can do without its structure. Examples include full-text search, word counts, change detection, plain-text email bodies and input for language processing. The main benefit is simple, portable output that any editor, terminal or pipeline can handle.

The cost is that meaning carried by markup is lost. That includes link targets, heading levels, emphasis, table relationships, image alternatives and language or direction attributes. If downstream readers or tools depend on any of these, either preserve them explicitly during extraction or keep the HTML alongside the text.

Plain output is the better choice when the destination cannot render HTML, when the text will be compared or searched, or when markup would expose content to injection in another context. Keep a structured format, such as cleaned HTML or Markdown, when the result will be read as a document rather than processed as data.

What the conversion actually changes

HTML-to-text extraction is neither reversal, mirroring nor a font change. It changes the stored characters in four ways. Tags are removed. Character references are decoded into real characters. Whitespace is collapsed or reflowed. Some block elements may be replaced with line breaks or margins, depending on the tool. The words themselves are not altered, so the order of the characters within a text node is the same as in the source.

Anything the page did through presentation alone is not carried over, because CSS is not applied:

  • Text hidden with CSS, such as display:none, can appear in the output, since the extractor reads the markup rather than the rendered page.
  • Visual reordering by CSS, such as flexbox order or absolute positioning, is lost. Text comes out in source order, which may differ from what a visitor sees.
  • Text added by CSS generated content does not appear, because it is not in the markup.
  • Case changes applied with text-transform are not applied. Text keeps the case it has in the source.

Bidirectional text needs separate attention. Logical character order is preserved, so right-to-left words remain correctly stored. However, the dir attribute and isolating elements such as bdi are dropped. Without them, mixed-direction lines may display differently in a plain-text viewer than they did on the page. Any Unicode direction control characters already in the text pass through unchanged, and they are invisible in most editors.

Common Perl approaches

Approach | What it does | Main tradeoff
Regex substitution, such as s/<[^>]*>//g | Deletes anything that looks like a tag | Breaks on comments, script and style blocks, and attributes containing >; leaves entities undecoded
HTML::Strip | Removes tags with a dedicated stripper | Gives no control over layout; check how the installed version handles entities and script content
HTML::TreeBuilder with as_text | Parses into a tree and joins the text nodes | Reliable parsing, but structure is flattened and link targets are omitted
HTML::TreeBuilder with HTML::FormatText | Parses, then lays text out with margins and line breaks | More readable output; behavior for tables and forms should be checked in the documentation for your version

For most work, a real parser is the safer foundation. Regex stripping can look correct on simple input, but it fails unpredictably on real pages.

A parser-based example

The following example decodes the input bytes, builds a tree, removes script and style elements, and formats the rest as plain text. It assumes the input is UTF-8. If your source declares another encoding, adjust the decode call.

use strict;
use warnings;
use Encode qw(decode);
use HTML::TreeBuilder;
use HTML::FormatText;

my $html = decode('UTF-8', $raw_bytes);

my $tree = HTML::TreeBuilder->new_from_content($html);
$_->delete for $tree->look_down(_tag => qr/^(?:script|style)$/);

my $formatter = HTML::FormatText->new(leftmargin => 0, rightmargin => 72);
my $text = $formatter->format($tree);
$tree->delete;

binmode STDOUT, ':encoding(UTF-8)';
print $text;

The code removes script and style elements explicitly rather than relying on module defaults, so the intent is visible to anyone reading it. It also deletes the tree at the end. HTML::Element documentation recommends this to release memory in long-running processes.

Entity decoding is one transformation you can check directly. HTML::Entities provides decode_entities, which turns a string such as Café & bar into Café & bar. Parsers built on HTML::Parser decode entities in text content for you. A regex-only approach does not, so it needs this step added separately.

Keeping web addresses during extraction

Link targets live in the href attribute, not in the link text, so text-only extraction drops them. If the addresses matter, collect them from the tree before formatting. You can then append each target after its label or gather all targets into a separate list.

for my $link ($tree->look_down(_tag => 'a', href => qr/./)) {
    my $label = $link->as_text;
    my $href  = $link->attr('href');
    $link->replace_with("$label [$href]");
}

Run this loop before you pass the tree to the formatter. Relative addresses stay relative. If the text will be read away from the original page, resolve them against the page's base address, for example with the URI module's new_abs method. Also decide how to handle fragment-only links and javascript: targets, which usually carry no value in plain text.

Readability and usability after copying or sharing

Plain text copies and pastes predictably, because it contains no formatting to lose. Screen readers read it as a continuous stream. That is reliable, but it removes the structural cues that well-built HTML gives assistive technology.

  • Headings: their levels are lost, so screen reader users can no longer jump between sections. Add blank lines or text markers if navigation matters.
  • Lists and tables: they are flattened, and table cells can run together. A reader may not be able to tell which value belongs to which column.
  • Images: image alt text may be dropped or replaced with a placeholder, depending on the tool. Check this before relying on the output for accessibility.
  • Language: lang attributes are discarded, so a screen reader may pronounce passages in other languages with the wrong voice.
  • Hidden content: text hidden by CSS can appear in the output, and so can text meant only for assistive technology, which may confuse sighted readers.

Plain output is generally helpful for search and editing, since the words are stored as ordinary characters. Two exceptions are worth checking. First, source-order differences can produce sentences that read oddly when CSS had reordered content. Second, invisible characters, such as zero-width spaces or direction controls, can survive conversion and interfere with matching. Normalizing whitespace and stripping control characters after extraction reduces both problems.

When the text will be published or read by people rather than processed by software, provide a structured version alongside it, or keep the original page available. This matters most for documents with tables, forms or mixed-direction text.

Gaps in this review

No measured comparisons were available, covering speed, memory use or output quality across modules, and no tests against specific screen readers or destination platforms. Behavior for tables, images and whitespace can differ between module versions. Run the extraction on a representative sample of your own pages and review the output before adopting it.