LWP::Simple提供許多簡便的方法讓我們下載網頁,以下介紹幾種
一、getstore, get, getprint
二、head
三、mirror

程式碼
use LWP::Simple;
my $url='http://www.perl.com/CPAN/SITES.html';
getstore($url, 'SITES.html');
getstore($url);
getprint($url);

getstore的方法很簡單,第一個參數是一個URL,你可以參考前面的利用URI::URL來處理URL來產生一個URL,或是如範例中直覺的寫法也行,第二個參數是你自行命名的一個檔案名稱。getstore會將你指定的文件存成本機的文件,就這麼簡單。

get方法若存取失敗會傳回undef

getprint方法會將取得的文件顯示於螢幕上

head方法實作了HTTP(參閱常用的HTTP回應碼)的HEAD要求方法,會傳回HTTP標頭,若無法取得文件則傳回undef。下面是head示範:
my($content_type, $document_length, $modified_time, $expires, $server)=head($url);

mirror方法和getstore一樣,但是只有在這份文件從上次取得之後被更改時,mirror才會將這份文件取回來,可見得這個在做文件的映射(mirror)時是很有用的。

最後給一個較長的範例,這程式可以找出網站的伺服器
use LWP::Simple;
use URI::URL;

die "usage:which_http host [host..]\n" unless @ARGV;
foreach my $host(@ARGV){
my $url=URI::URL->new($host);
my @headers=head($url);
if(@headers){
print "Host: $host\n";
print "Server: @{[pop @headers]}\n\n";
}else{
print "Unable to retrive @{[$url->as_string]}\n\n";
}
}



執行結果
c:\>perl zz.pl http://www.microsoft.com http://blog.pixnet.net
Host: http://www.microsoft.com
Server: Microsoft-IIS/6.0

Host: http://blog.pixnet.net
Server: Apache

pixnet的主機是Apache Web Server :)
arrow
arrow
    全站熱搜

    jck11 發表在 痞客邦 留言(0) 人氣()