Perl で、サイトにアクセスして HTML を取得する方法

LWP (libwww-perl という形で配布されている) を使う。LWP::Agent モジュールは、ウェブクライアント、ウェブオートメーション (ソフトウェアやプログラムが自動的にサイトにアクセスして情報を取ってくること) といったものの基本である。もうはるか彼方、何年も前からある技術なのに基本は変わっていないのがポイント。以下のスクリプトは、$URL で指定されているサイトにアクセスして、成功すればその HTML のコードをコンソールに表示、失敗したときはエラーコードを出力する例。CGI として機能させたときは、ブラウザには HTML コードでなく $URL でアクセスしたページを表示する。つまりプロキシとして動作するということ。

シンプルなバージョン

#!/usr/bin/perl use LWP::UserAgent; use HTTP::Request; use HTTP::Response; our $URL = 'https://perltips.twinkle.cc/'; # アクセスする URL my $proxy = new LWP::UserAgent; my $req = HTTP::Request->new('GET' => $URL); # HTTP リクエストを作成 my $res = $proxy->request($req); # $res に HTTP レスポンスが返ってくる print $res->content; # HTML を表示 1;

ちょっと長いバージョン

#!/usr/bin/perl use LWP::UserAgent; use HTTP::Request; use HTTP::Response; our $URL = 'https://perltips.twinkle.cc/'; # アクセスする URL my $proxy = new LWP::UserAgent; $proxy->agent('your own created browser name here'); # 任意 $proxy->timeout(60); # 任意 my $req = HTTP::Request->new('GET' => $URL); my $res = $proxy->request($req); my $content = $res->content; print "Content-Type: text/html\n\n"; # HTML ヘッダ (CGI として動作できる) if($res->is_success) {
print $content;
} else {
print 'HTTP エラーコード: ' . $res->code;
} 1;
参考書とリンク

<iframe src="https://xml-jp.amznxslt.com/onca/xml?Service=AWSECommerceService&ItemId=4900900621&AWSAccessKeyId=152ZP71KPB47XM09CS02&AssociateTag=twinklexxx-22&Operation=ItemLookup&IdType=ASIN&ContentType=text%2Fhtml&Version=2006-03-08&Page=1&ResponseGroup=ItemAttributes,Images,Offers&Style=https://perltips.twinkle.cc/files/sites/perltips/xsl/amazon.xsl" scrolling="no" marginwidth="0" marginheight="0" frameborder="0" height="160"></iframe> <iframe src="https://xml-jp.amznxslt.com/onca/xml?Service=AWSECommerceService&ItemId=4873112028&AWSAccessKeyId=152ZP71KPB47XM09CS02&AssociateTag=twinklexxx-22&Operation=ItemLookup&IdType=ASIN&ContentType=text%2Fhtml&Version=2006-03-08&Page=1&ResponseGroup=ItemAttributes,Images,Offers&Style=https://perltips.twinkle.cc/files/sites/perltips/xsl/amazon.xsl" scrolling="no" marginwidth="0" marginheight="0" frameborder="0" height="160"></iframe> <iframe src="https://xml-jp.amznxslt.com/onca/xml?Service=AWSECommerceService&ItemId=4873112036&AWSAccessKeyId=152ZP71KPB47XM09CS02&AssociateTag=twinklexxx-22&Operation=ItemLookup&IdType=ASIN&ContentType=text%2Fhtml&Version=2006-03-08&Page=1&ResponseGroup=ItemAttributes,Images,Offers&Style=https://perltips.twinkle.cc/files/sites/perltips/xsl/amazon.xsl" scrolling="no" marginwidth="0" marginheight="0" frameborder="0" height="160"></iframe>

Web クライアントプログラミングの本は、タイトルには 「Web プログラミング」 とついているものの、中身は LWP の解説本です。

Comments