URLをタイトルに変換する大雑把な仕掛け(Perl)
2011-07-11-5
[Programming]
与えられたURLのページタイトルを取得するための大雑把な仕掛けです。その場しのぎな状況で、コピペしてよく使うのでここにメモしておきます。
■コード(url2title.pl)
■実行例
■コード(url2title.pl)
#!/usr/bin/perl
use strict;
use warnings;
use LWP::UserAgent;
use Encode;
use Encode::Guess qw/shift-jis euc-jp 7bit-jis/;
use utf8;
binmode STDOUT, ":utf8";
while (<>) {
chomp;
next if not /^http/;
print url2title($_), "\n";
}
sub url2title {
my ($url) = @_;
my $ua = LWP::UserAgent->new(timeout => 5);
my $req = HTTP::Request->new(GET => $url);
$req->header('Accept' => 'text/html');
my $res = $ua->request($req);
return $url if not $res->is_success;
my $title = $url;
if ($res->content =~ m{<title>(.+?)</title>}smi) {
$title = $1;
$title =~ s/[\t\n\r]+/ /g;
my $decoder = Encode::Guess->guess($title);
if (ref($decoder)) {
$title = $decoder->decode($title);
} else {
$title = Encode::decode('utf8', $title);
}
}
return $title;
}
■実行例
% cat url.txt http://www.yahoo.co.jp/ http://chalow.net/ http://www.hatena.ne.jp/ % ./url2title.pl url.txt Yahoo! JAPAN たつをの ChangeLog はてな
