Journal(2005) | Blog(2006) | RandomLink | WhoAmI | LiveBookmark | HomePage

<<Previous: Ajax && encodeURIComponent  >>Next: Synopsis localization

获取 IRC logger 里的链接

Category: Script   Keywords: irclogger link

PerlChina 的 IRC 位于 irc://irc.freenode.net/perlchina
因为我不能长时间在线,又不想错过什么精彩链接,就写了这份代码来解析 IRC log 里的链接。
代码位于 http://www.fayland.org/scripts/irc_link.pl.txt

代码解释

首先 IRC log 的地址都是变动的,比如今天 irclogger 的地址为 http://koala.ilog.fr/twikiirc/bin/irclogger_log/perlchina?date=2005-05-18,Wed 明天后缀又会改。
所以我们先用 DataTime 来拼凑这个 URL.
my $dt = DateTime->now;
my $url = 'http://koala.ilog.fr/twikiirc/bin/irclogger_log/perlchina?date=' . $dt->ymd . ',' . $dt->day_abbr; # like 2005-05-18,Wed
$dt->ymd 得到类如 2005-05-18 格式,而 $dt->day_abbr 得到星期的简写。

第二是使用 LWP 获取网页,因为这个 irclogger 需要验证,所以代码稍微复杂了点。
use LWP;
use vars '@ISA'; # for get_basic_credentials
@ISA = 'LWP::UserAgent';
my $agent = __PACKAGE__->new;
my $request = HTTP::Request->new(GET => $url);

my $response = $agent->request($request);
$response->is_success or die $response->message;

sub get_basic_credentials {
    return ('perlchina', 'perlchina'); # the perlchina irc log site's username&password
}
这里我们重载了 LWP::UserAgent 的 get_basic_credentials 函数。这样就能通过基本的 Web 验证了。

最后获取连接,我没有使用现成的模块,而是用强大的 HTML::Parser 来解析出链接。
use HTML::Parser;

my $parser = HTML::Parser->new(api_version => 3);
$parser->handler(start => \&got_links, 'tagname, attr');
$parser->parse($response->content);
$parser->eof;

sub got_links {
    my ($tagname, $attr) = @_;
    if ($tagname eq 'a' && $attr->{href} && $attr->{href} !~ /^[\/\?]/) {
        print '<a href=\'', $attr->{href}, '\'>', $attr->{href}, '</a><br />';
    }
}
$attr->{href} !~ /^[\/\?]/) 是忽略掉以/和?开头的链接(这些是那页面的内部链接)。
详细的代码解释就免了,perldoc 里都有简单的例子。

So, Enjoy

<<Previous: Ajax && encodeURIComponent  >>Next: Synopsis localization

Options: +Del.icio.us

Related items Created on 2005-05-18 22:09:00, Last modified on 2005-05-18 22:11:17
Copyright 2004-2005 All Rights Reserved. Powered by Eplanet && Catalyst 5.62.