Hi Monks!!
I am trying to use HTML::Parser to extract data of specified HTML tag:
use strict;
use HTML::Parser;
my $content=<<EOF;
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Some title goes here</title>
</head>
<body bgcolor="#FFFFFF">
<div id="leftcol">
menu column
</div>
<div id="body">
<p>some text goes here some text goes here<br />
some text goes here some text goes here</p>
<p><strong>some header</strong></p>
<p>some text goes here some text goes here<br />
some text goes here some text goes here</p>
<p><img src="img.gif" /> image here</p>
<p><strong>some header</strong></p>
<p>some text goes here some text goes here<br />
some text goes here some text goes here</p>
</div>
<div id="rightcol">
news column
</div>
</body>
</html>
EOF
my $p = HTML::Parser->new( api_version => 3 );
$p->handler( start => \&start_handler, "self,tagname,attr" );
$p->parse($content);
exit;
sub start_handler {
my $self = shift;
my $tagname = shift;
my $attr = shift;
return unless ( $tagname eq 'div' and $attr->{id} eq 'body' );
$self->handler( text => sub { print shift }, "dtext" );
$self->handler(end => sub { shift->eof if shift eq $tagname; }, "
+tagname,self");
}
In this simplified example it strips HTML inside the <div id="body">...</div> and prints out just text, but I need all html formatting to be untouched. How to achieve this?
Thanks! :)
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.