Hello Monks,

I am trying to parse html text with tags intact. The code I wrote using HTML::Parser strips out the tags.

Is there a way to keep tags intact?

below is my code.

#!/usr/bin/perl package MyParser; use base qw(HTML::Parser); my $main_content=""; sub start { my ($self, $tag, $attr, $attrseq, $origtext) = @_; if ($tag =~ /^span$/i && $attr->{'class'} =~ /^main-content$/i +) { # set if we find <span class="main-content" $content_flag = 1; } } sub text { my ($self, $text) = @_; # If we're in <H1>...</H1> or if ($content_flag) { $main_content .= $text; } } my $html = " <html> <head> <title>Blah</title> </head> <span class=\"main-content\"> <bold_text> Here's the body 1 </bold_text> <p> para1 </p> <p> para2 </p> </span> </html>"; my $parser = MyParser->new; $parser->parse("$html"); print "$main_content\n";

Output I get:

Here's the body 1 para1 para2

Output I need is:

<bold_text> Here's the body 1 </bold_text> <p> para1 </p> <p> para2 </p>

I would like the above output to still have tags, is it possible to do this with HTML::Parser?


In reply to Parsing HTML with tags intact by mr_p

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.