【Chapter2】LWP的Simple

来源:互联网 发布:风险矩阵法公式 编辑:程序博客网 时间:2024/05/29 17:41

 

LWP的Simple用于实现基本的HTTP方法,Simple的接口简单,也只能实现一些基本的操作。

 

【getstore抓页面并保存】

例2-1 getstore抓页面并保存

#!usr/bin/perl

use LWP::Simple;

 

my $url='http://www.sina.com.cn’;

my $file='/web.html';

 

my $status=getstore($url,$file);

 

运行完了神马都木有显示,不过在路径下生成了一个web.html,打开一看就是我们的URL的页面。

 

为了显示抓取是否成功,加一行

 

print "Success $status on $url" if is_success($status);

 

status在200-299之间都是true,打印出来:

status在400-599之间都是false。

【getprint打印】

将2-1的代码改一改

 

my $status=getprint($url);

结果是将页面打印出来:

 

如果用get呢?

my $status=get($url);

结果跟getprint是一样的......- -#一样的干嘛要用两个函数。哦,返回值不一样。

 

【使用head方法】

例2-2 head方法

#!usr/bin/perl

use LWP::Simple;


my $url='http://hi.csdn.net/space.php';
my $file='web.html';
my $is_success = head($url);

die "failed on $url" unless head($url);
print "$is_success.";

打印出来是:

 

这是个神马东西呢?在列表上下文环境中,head函数在请求成功时会返回一个五元组:
(content_type, document_length, modified_time, expires, server)=head(url);

如上图所示的一个列表。列表上下文环境中,如果head函数请求失败时,返回为空列表。

那么我们来打印一下看看,

 

my ($param1,$param2,$param3,$param4,$param5) = head($url);
print "$param1/n,$param2/n,$param3/n,$param4/n,$param5.";

好多地方都是空的哦,不过,有内容的两个可以得知,一个是MIME类型,一个是SERVER。

 

【head的更多用法】

例2-2 看看head里面的最后修改时间

#!usr/bin/perl
use strict;
use LWP::Simple;

my $moment = time();
foreach my $url (
'http://bbs.auxten.com',
'http://www.sina.com.cn',
)
{
print "/n$url/n";

my ($type, $length, $mod) = head($url);

print "That $type document is ", $length || "???", " bytes long./n";
if ($mod) {
my $ago = $moment-$mod;
print "It was modified $ago seconds ago; that’s about ",
int(.5 + $ago / (24 * 60 * 60)), " days ago, at ",
scalar(localtime($mod)), "!/n";
} else {
print "I don’t know when it was last modified./n";
}
}

 

打印出来是这样滴

有的拿不到最后修改时间,不知道为什么。

原创粉丝点击