HTML::Parser
HTMLページを解析する
use HTML::parser;
パッケージをロードする。日本語のページを解析する場合は、utf8に変換してから解析すること。
使い方:
use utf8;
binmode STDOUT,":utf8";
my $ps = HTML::Parser->new( api_version => 3, handler_name => [ \&handler , "argument
, …"] , …);
open (my $fh , "<:utf8", $html_file) || die "file open
error\n";
$ps->parse_file($fh);
ファイルや文字列が既に
utf8エンコードされていれば、下記の様な簡単な書式でも呼び出せる。
$ps->parse_file($fileName);
$ps->parse($string);
handler_nameとargumentには、下記のニーモニックを指定する。handler_nameに対応するイベントが発生した時に&handlerがargumentを引数にしてコールされる。
同じ構造のHTMLを繰り返し解析する用途には、HTML::TreeBuilder
の方が向いている。
handler_name | イベント | argument | |||
tag | tagname | attr | text | ||
start_document_h | 解析開始時 | undef | undef | undef | undef |
end_document_h | 解析終了時 | undef | undef | undef | undef |
declaration_h | DOCTYPEタグ検出時 | !doctype | doctype | undef | タグ全体 |
start_h | 開始タグ検出時 | タグ 例:html |
タグ 例:html |
タグパラメタを切り出したハッシュへの参照 | タグ全体 |
end_h | 終了タグ検出時 | タグ 例:/html |
タグ 例:html |
undef | タグ全体 |
comment_h | コメントタグ検出時 | ゴミ※ | ゴミ※ | undef | タグ全体 |
text_h | テキスト検出時 | undef | undef | undef | テキスト文字列 |
default_h | ハンドラ未定義イベント | 検出イベントに依存 |
※コメント文字列をタグとパラメタ風に解釈して渡してくる
上記以外の主なargument
line:イベントが発生した行(先頭行は1)
self:HTML::Parseオブジェクト
skipped_text:前回イベント以降にスキップされたテキスト
使用例:
my $ps = HTML::Parser->new(api_version=>3, start_h => [\&start ,"text,line,tag,tagname,attr"], end_h => [\&end,"text,line,tag,tagname"]); binmode STDOUT, ":utf8"; open(my $fh, "<:utf8", "./parse.html"); $ps->parse_file($fh); sub start { my $text = shift; my $line = shift; my $tag = shift; my $tagname = shift; my $attrr = shift; my %attr = %$attrr; print "START TAG=$tag TAGNAME=$tagname LINE=$line\n"; print "text=$text\n"; foreach my $key (keys %attr) { print "$key=$attr{$key}\n"; } print "---\n"; } sub end { my $text = shift; my $line = shift; my $tag = shift; my $tagname = shift; print "END TAG=$tag TAGNAME=$tagname LINE=$line\n"; print "text=$text\n"; print "---\n"; }