ページ更新: 2009-06-30 (火) (5017日前)
(2001-09-14 作成、2005-01-29 Wikiに移動して説明をちょっと修正) HTMLの外部リンクチェック HTMLのリンク切れを調べるPerlスクリプトを書いてみました。 開発+テスト環境は Windows2000 + ActivePerl v5.6.1-Build628、本番は Debian GNU/Linux Woody kernel 2.2.19 です。 目次 [編集]参考文献 #
仕様と方針 #
スクリプト ##!/usr/bin/perl use strict; use File::Find (); require HTML::LinkExtor; use LWP::Simple; ## begin configration my $documentroot= '/var/www'; my $siteurl= 'http://example.jp'; ## end configration ## listup HTML documents use vars qw/*name *dir *prune/; *name = *File::Find::name; *dir = *File::Find::dir; *prune = *File::Find::prune; my @filelist; sub callback_filefind { push @filelist, $name if /\.s?html?$/s; } File::Find::find({wanted => \&callback_filefind}, $documentroot); ## extract link, and check link my @linklist; sub callback_linkextor { my($tag, %links) = @_; if( $tag eq 'a' and ($links{'href'} =~ m!^http://!) and ($links{'href'} !~ m!^$siteurl!) ) { push @linklist, $links{'href'}; } } my @resultlist; for my $file (@filelist) { print "\nfile: $file\n"; @linklist = (); my $p = HTML::LinkExtor->new(\&callback_linkextor); $p->parse_file($file); for my $url (@linklist) { if (head($url)) { print " exist(HEAD) $url\n"; push @resultlist, { file => $file, url => $url, result => 'exist(HEAD)' }; } else { sleep 3; if (get($url)) { # for @nifty, etc. print " exist(GET) $url\n"; push @resultlist, { file => $file, url => $url, result => 'exist(GET)' }; } else { print " not exist: $url\n"; push @resultlist, { file => $file, url => $url, result => 'not exist' }; } } } } ## print '='x70,"\n"; for (@resultlist) { if( $_->{result} =~ /not exist/ ) { my $url= $_->{url}; my $file= $_->{file}; print "$file: $url\n"; } } ## end[編集] 課題 #Windows2000 + ActivePerlで動かしてリンクチェックは完了。普段はサーバ側でcronで起動するようにしたけど、もう少しましなものにしたい。
……というわけで、そういったコードの断片。未テスト。 use LWP::UserAgent; my $agentname = 'OuterLinkChecker/0.1 http://example.jp/'; #1 my $mailaddress= 'webmaster@example.jp'; #1 my @urlcache; sub myHeadGet { my ($method, $url) = @_; # urlから#を取る $url =~ s/^(.*?)#.*$/$1/; #3 # キャッシュを調べる # UserAgent組み立て my $useragent = LWP::UserAgent->new; $useragent->agent("$agentname $useragent->agent"); #1 $useragent->from($mailaddress); #1 # ヘッダ組み立て my $request; if ($method eq 'GET') { $request = HTTP::Request->new(GET => $url); } else { $request = HTTP::Request->new(HEAD => $url); } $request->header('Accept' => 'text/html'); # リクエストの送信 my $response= $useragent->request($request); # 出力 if (wantarray) { return ($response->code, $response->headers->last_modified); #4,7 } else { return $response->is_success; } } sub head { myHeadGet('HEAD', @_); } sub get { myHeadGet('GET', @_); }[編集] 同様の機能を持ってるっぽいソフトウェア #
|