2008年8月19日火曜日

HTML::Parser使い方

my @parsed = ();
&parseHTML($html);
#httpまたはhttpsからはじまるURLのみがprintされる
print @parsed, "\n\n";

sub parseHTML {
my $p = HTML::Parser->new(
api_version => 3,
start_h => [
sub {
my ($tagname, $attr, $text) = @_;
if ($tagname eq 'a') {
my $href = $attr->{href};
if ($href =~ /https?:/) {
push(@parsed, $href);
}
}
}, "tagname, attr, text"],

marked_sections => 1,
);
$p->parse(shift);
}

----------------------
コマンドからの入力

use HTML::Parser;
use Encode qw//;

my $html = Encode::decode("utf8", do { local $/ = undef; <>; });
my @parsed = ();
&parseHTML($html);
#httpまたはhttpsからはじまるURLのみがprintされる
print @parsed, "\n\n";

sub parseHTML {

my $p = HTML::Parser->new(
api_version => 3,
start_h => [
sub {
my ($tagname, $attr, $text) = @_;
if ($tagname eq 'a') {
my $href = $attr->{href};

push(@parsed, $href);

}
}, "tagname, attr, text"],

marked_sections => 1,
);
$p->parse(shift);
}

0 件のコメント: