use strict;
use utf8;
use encoding 'utf8', STDIN=>'utf8', STDOUT=>'utf8';
use Encode::Guess;
use Encode;
use WWW::Mechanize;
use HTTP::Response::Encoding;
my $url = 'http://blogs.itmedia.co.jp/';
my $mech = WWW::Mechanize->new();
$mech->get($url);
# 追うリンク階層数
my $linknum = 2;
use vars qw(%followed_link);
%followed_link = {}; # すでに辿ったかどうかのフラグ
getcontent($mech, $linknum);
exit();
sub getcontent($$)
{
my ($mech, $linknum) = @_;
# コンテンツを取得
if ($mech->success() && $mech->is_html())
{
# 内容を取得
my $content = $mech->content();
# レスポンスを取得
my $res = $mech->response();
# 文字コード変換
# 1. Content-Typeから判定
my @encoding =
$res->encoding,
($res->header('Content-Type') =~ /charset=(\w\-]+)/g);
my $enc;
foreach my $value (@encoding)
{
if (Encode::find_encoding($value))
{
# 定義されているものが見つかった
$enc = $value;
last;
}
}
# 2. 見つからない場合は自動判定
if (!defined $enc)
{
Encode::Guess->setsuspects(qw/shift-jis euc-jp 7bit-jis/);
$enc = "Guess";
}
$content = Encode::decode($enc, $content);
# 先頭500文字を表示
print substr($content, 0, 500);
# 内部リンクの数だけ繰り返す
$linknum--;
if ($linknum > 0)
{
foreach my $link ($mech->find_all_links(url_abs_regex => qr#^http://blogs.itmedia.co.jp/#))
{
# リンク先を辿る
my $url = $link->url();
if (!$followed_link{$url})
{
$followed_link{$url} = 1;
print "-- GET " . $url . "\n";
$mech->get($link->url());
getcontent($mech, $linknum);
}
# 戻る
$mech->back();
}
}
}
}
Copyright © ITmedia, Inc. All Rights Reserved.