| ホーム > 技術情報 > ニュースサイトのRSSを1つのHTMLにまとめる | 検索 | 更新情報 |
| Perlの入門書 | メーリングリスト | 著書 |
Jcode, LWP::Simple, それにXML::RSSを使い、 「あちこちのニュースサイトのRSSを取得して1つのHTMLにまとめる」 というPerlスクリプトです。
以下の例では、RSSは、 いがぴょんさん、 宮川さんのところから取得しています。
#
# make_rss_news.pl
#
use strict;
use Jcode;
use XML::RSS;
use LWP::Simple;
my $maxcount = 5;
my @site = (
{ name => 'www.textfile.org',
link => 'http://www.textfile.org/',
rss => 'http://www.hyuki.com/tf/tf.xml',
from => 'http://www.textfile.org/', },
{ name => 'www.asahi.com',
link => 'http://www.asahi.com/',
rss => 'http://bulknews.net/rss/rdf.cgi?Asahi',
from => 'http://bulknews.net/', },
{ name => 'ZDNN:ニュース速報',
link => 'http://www.zdnet.co.jp/news/bursts/index.html',
rss => 'http://homepage2.nifty.com/igat/igapyon/diary/rss/demozdnnnews.rss1.0.xml',
from => 'http://homepage2.nifty.com/igat/igapyon/', },
);
my @result = (
# { sitename => '',
# sitelink => '',
# title => '',
# link => '',
# description => '', },
);
for my $site (@site) {
print STDERR "Retrieving $site->{name}...\n";
my $rss = new XML::RSS;
my $content = get($site->{rss});
unless ($content) {
print "ERROR\n";
next;
}
$rss->parse($content);
my $count = 0;
foreach my $item (@{$rss->{items}}) {
my $hash = {
sitename => &sjis($site->{name}),
sitelink => &sjis($site->{link}),
};
$hash->{title} = &sjis($item->{title});
$hash->{link} = &sjis($item->{link});
$hash->{description} = &sjis($item->{description});
push(@result, $hash);
$count++;
if ($count >= $maxcount) {
last;
}
}
}
my $text = <<"EOD";
<html>
<h1>News</h1>
EOD
my $sitename = '';
$text .= "<h2>Index</h2><ul>";
foreach my $data (@result) {
if ($sitename ne $data->{sitename}) {
$text .= qq|<li><a href="#$data->{sitelink}">$data->{sitename}</a></li>\n|;
$sitename = $data->{sitename};
}
}
$text .= "</ul>\n";
$sitename = '';
foreach my $data (@result) {
if ($sitename ne $data->{sitename}) {
if ($sitename) {
$text .= qq|</ul>\n|;
}
$text .= qq|<h2><a name="$data->{sitelink}" href="$data->{sitelink}">$data->{sitename}</strong></a></h2>\n<ul>\n|;
$sitename = $data->{sitename};
}
$text .= qq|<li><a href="$data->{link}">$data->{title}</a></li>\n|;
}
$text .= <<"EOD";
</ul>
</html>
EOD
print $text;
sub sjis {
my $text = shift;
return Jcode->new($text)->sjis;
}
以下のように実行します。
C:WORK> perl make_rss_news.pl > sample.html Retrieving www.textfile.org... Retrieving www.asahi.com... Retrieving ZDNN:ニュース速報...
結果のHTMLは次のようになります。
あなたのご意見・感想をお送りください。 あなたの一言が大きなはげみとなりますので、どんなことでもどうぞ。