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; }
One=Monday, Six=Saturday, Three=Wednesday, Five=Friday, Two=Tuesday, S +even=Sunday , Four=Thursday,
In reply to Re: Parsing HTML/XML with Regular Expressions (HTML::Parser)
by fishy
in thread Parsing HTML/XML with Regular Expressions
by haukex
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |