For my purposes, the as_text method of HTML::Element was somewhat insufficient, as I wanted to exempt specific tags from having their content added to the text, and I wanted to be able to place a delimiter where tags once where. So, I created my own tree2text subroutine:my $html = ... my $tree = HTML::TreeBuilder->new; $tree->parse($html); my $text = $tree->as_text();
You may also find my recent meditation regarding evil spaces to be of value in your endeavour.# delim => delimiter to replace stripped tags # escaped_delim => text to escape delimiter with if present in content # skip_tags => tags for which content is not added to text, # defaults to 'script' and 'style' # sub tree2text { my ($tree, %options) = @_; my $delim = defined $options{delim} ? $options{delim} : ''; my $esc_delim = $options{escape_delim}; my $skip = $options{skip_tags} || ['script', 'style']; my @skip = map { lc } @$skip; my @nodes = ($tree); my ($tag, $text); $text = ''; while (@nodes) { my $node = shift @nodes; if (!defined $node) { # move along } elsif (!ref $node) { $node =~ s/$delim/$esc_delim/g if defined $esc_delim; $text .= $delim.$node; } else { $tag = $node->tag; next if grep { $tag eq $_ } @skip; unshift @nodes, $node->content_list; } } return $text; }
MeowChow s aamecha.s a..a\u$&owag.print
In reply to Re: HTML::Parse
by MeowChow
in thread Getting HTML::Parse to work (was: HTML::Parse)
by DarkBlue
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |