HTML::Parserでリンク情報取得

指定したサイトのHTMLを解析して、リンク情報を抜き出すスクリプト
HTML::Parserを初めて使った。

#!/opt/local/bin/perl

use strict;
use warnings;
use LWP::UserAgent;
use HTTP::Request;
use HTML::Parser;

my $url = shift;
my $req = HTTP::Request->new(
    GET => "$url"
);
my $ua = LWP::UserAgent->new;
my $res = $ua->request($req);
my $content = $res->content if ($res->is_success);

my $p = HTML::Parser->new(
    api_version => 3,
    start_h => [
	sub {
	    my ($self, $tagname, $attr, $text) = @_;
	    if ($tagname eq 'a') {
		my $href = $attr->{href} || '';
		print "$href\n" if ($href =~ /^(http:|https:)/);
	    }
	}, "self, tagname, attr, text"],
    marked_sections => 1,
);

$p->parse($content);


HTML::Parser - HTML parser class - metacpan.org