【Chapter4】还是do_GET

来源:互联网 发布:广联达软件好学吗 编辑:程序博客网 时间:2024/05/21 16:30

 一种常见的LWP的使用就是使用UserAgent模板(还是类?)。

【抓取页面的例子】

例4-1 抓取一个页面并判断是否有某个特定字符串
#!usr/bin/perl
use LWP::UserAgent;
my $browser = LWP::UserAgent->new( );
$browser->env_proxy( ); # 如果在防火墙后
$url = 'http://www.sina.com.cn/';
my $response = $browser->get($url);
die "cannt get! /"", $response->status_line( ),
"/" when getting $url"  unless $response->is_success( );

my $content_type = $response->content_type( );
die "Hm, unexpected content type $content_type from $url"
unless $content_type eq 'text/html';
my $content = $response->content( );
die "Odd, the content from $url is awfully short!"
 if length($content) < 3000;
if($content =~ m/情感专家谈单身如何提高“爱商”/) {
 print "<!-- The news today is IMPORTANT -->/n";
} else {
   print "$url has no news of ANY CONCEIVABLE IMPORTANCE!/n";
}

 

打印结果是:

这段代码检查页面中是否包含字符串"情感专家谈单身如何提高“爱商”,如果有,就打印“今天的新闻很重要哦”

【试试do_GET do_POST】

例4-2 一个典型的do_GET实现

use LWP;
my $browser;
sub do_GET {
$browser = LWP::UserAgent->new( ) unless $browser;
$browser->env_proxy();
#获取响应列表
my $response = $browser->request(@_);
#获取响应列表:
return($response->content, $response->status_line, $response->is_success, $response) if wantarray;
#如果获取失败,则返回
return unless $response->is_success;
#如果获取成功,则返回内容(表单)
return $response->content; }

do_POST和do_GET方法差不多,只是实现的时候,将get方法改为post(?)这句话什么意思?

原创粉丝点击