Hi Monks,
someone had to try with HTML::Parser... Here I am:
use warnings;
use strict;
use HTML::Parser;
my $parser = HTML::Parser->new(
api_version => 3,
start_h => [\&start_handler, "self, tagname, attr"]
+,
strict_names => 1,
empty_element_tags => 1,
);
my $file = "1201438.html";
open(my $fh, "<", $file) or die "Can't open < $file: $!";
my $contents = do { local $/; <$fh> };
close $fh;
$parser->parse($contents);
for (keys %{$parser->{_numbers}}) {
print "$_=", join("", @{$parser->{_numbers}->{$_}}), ", ";
}
print "\n";
sub start_handler {
my ($self, $tag, $attr) = @_;
return unless $tag eq 'div';
$self->handler(start => \&number_start_handler, "self,tagname,attr")
+;
}
# <div class="data" id="Zero" />
sub number_start_handler {
my ($self, $tag, $attr) = @_;
if ( exists $attr->{class}
&& $attr->{class} eq 'data'
&& exists $attr->{id}
&& $attr->{id} =~ /(Zero|One|Two|Three|Four|Five|Six|Seven)/ )
+{
$self->{_now} = $1;
$self->{_numbers}->{$1} = [];
$self->handler(text => \&number_text_handler, "self,text");
} elsif ($tag eq 'b') {
$self->handler(text => \&number_text_handler, "self,text");
} elsif ($tag eq 'div'
&& ! exists $attr->{class} ) {
$self->handler(text => \&number_text_handler, "self,text");
} else {
$self->handler(text => undef);
}
}
sub number_text_handler {
my ($self, $text) = @_;
$text =~ s/^\s+//;
$text =~ s/\s+$//;
push @{$self->{_numbers}->{$self->{_now}}}, $text;
}
No perfect output:
One=Monday, Six=Saturday, Three=Wednesday, Five=Friday, Two=Tuesday, S
+even=Sunday , Four=Thursday,
If someone could give me some hint why I miss 'Zero' and don't get right 'Sunday'?
Thanks!
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.