首页 技术 正文
技术 2022年11月15日
0 收藏 411 点赞 4,161 浏览 5396 个字

LWP::UserAgent是一个模拟用户浏览器的类,在使用的时候需要遵守以下几步:

1、引入模块

2、创建一个LWP::UserAgent的对象

3、设置这个对象的相关参数

4、创建HTTP::Request实例

5、发送请求

6、返回HTTP::Response对象。

1、引入模块

use LWP::UserAgent;

2、创建一个LWP::UserAgent对象

$ua = LWP::UserAgent->new( %options )
options的键值如下:
KEY             DEFAULT
-----------     --------------------
agent           "libwww-perl/#.##"
from            undef
conn_cache         undef
cookie_jar         undef
default_headers      HTTP::Headers->new
max_size          undef
max_redirect        
parse_head         
protocols_allowed     undef
protocols_forbidden    undef
requests_redirectable  ['GET', 'HEAD']
timeout           5

另外,如果env_proxy的值设为真,那么代理设置将有效(参见env_proxy());如果keep_alive为真,那么LWP::ConnCache将建立(参见conn_cache())。

$ua->clone 返回LWP::UserAgent对象的一个拷贝

3、设置LWP::UserAgent对象的相关参数
(1) $ua->agent
$ua->agent( $product_id )
用来返回或者设置用户的agent,用来在header中告诉服务器你用的是什么”浏览器”,设置文件头的User-Agent。缺省值是 _agent()返回的字符串。

如果$product_id以空格结尾,那么_agent()的返回值将加到$product_id后面。user-agent必须是以/分割的浏览器名+版本号,如:

$ua->agent('Checkbot/0.4 ' . $ua->_agent);
$ua->agent('Checkbot/0.4 '); # same as above
$ua->agent('Mozilla/5.0');
$ua->agent(""); # don't identify

$ua->_agent返回缺省的agent值,形如”libwww-perl/#.##”

(2)$ua->from
$ua->from( $email_address )
返回或者设置发起请求的人的邮件地址,设置文件头的from。如:
$ua->from(‘gaas@cpan.org’);
默认设置是不发送from键值

(3)$ua->cookie_jar
$ua->cookie_jar( $cookie_jar_obj )
返回或者设置cookie,在运行过程中必须执行两个方法,extract_cookies($request) 和 add_cookie_header($response)。在运行的过程中实际用到了HTTP::Cookies模块。如:
$ua->cookie_jar({ file => “$ENV{HOME}/.cookies.txt” });
等价于
require HTTP::Cookies;
$ua->cookie_jar(HTTP::Cookies->new(file => “$ENV{HOME}/.cookies.txt”));

(4)$ua->default_headers
$ua->default_headers( $headers_obj )
设置或返回每一次请求的headers值,缺省是一个空的HTTP::Headers 对象
$ua->default_headers->push_header(‘Accept-Language’ => “no, en”);
$ua->default_header( $field )
$ua->default_header( $field => $value )

如:
my %headers=('Accept'=>'image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/QVOD, */*',
'Accept-Language'=>'zh-cn',
'User-Agent'=>'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727)',
'Accept-Charset' => 'iso-8859-1,*,utf-8');
my $response = $browser->get($url,%headers);

(5)$ua->conn_cache
$ua->conn_cache( $cache_obj )
设置或返回LWP::ConnCache 对象

(6)$ua->credentials( $netloc, $realm, $uname, $pass )
设置访问一个域的时候的用户名和密码
(7)$ua->max_size
$ua->max_size( $bytes )
设置或返回响应内容的大小。缺省是undef,意思是不限制。
(8)$ua->max_redirect
$ua->max_redirect( $n )
设置或返回被请求页面所跳转的最大次数。默认为7
(9)$ua->parse_head
$ua->parse_head( $boolean )
设置或返回是否我们初始化响应的HTML的<head></head>标签内容。默认是TRUE,不要将这个值关闭,除非你知道你在做什么。
(10)$ua->protocols_allowed
$ua->protocols_allowed( \@protocols )
设置或返回发起请求的方法,方法名对大小写敏感。例如$ua->protocols_allowed( [ ‘http’, ‘https’] ); 表明该用户只允许这两种协议。如果用其他的协议访问URL(like “ftp://…”)将会导致500错误
删除这个设置的方法: $ua->protocols_allowed(undef)
(11)$ua->protocols_forbidden
$ua->protocols_forbidden( \@protocols )
(12)$ua->requests_redirectable
$ua->requests_redirectable( \@requests )
push @{ $ua->requests_redirectable }, ‘POST’;告诉LWP在POST请求发送后如果发生重新定向就自动跟随
(13)$ua->timeout
$ua->timeout( $secs )
设置缓冲时间,默认5s


4、请求方法
(1)$ua->get( $url )
$ua->get( $url , $field_name => $value, … )
:content_file => $filename 将返回的文件按照$filename保存下来,对大文件应该如此,不然保存在内存中。
:content_cb => \&callback callback执行的函数,这个选项与:content_file只能设置其一。
:read_size_hint => $bytes
如:$response=$ua->get(‘http://search.cpan.org/’,’:content_file’=>’/tmp/sco.html’)
(2)$ua->head( $url )
$ua->head( $url , $field_name => $value, … )
(3)$ua->post( $url, \%form )
$ua->post( $url, \@form )
$ua->post( $url, \%form, $field_name => $value, … )
如:$response = $browser->post( $url,[formkey1 => value1,formkey2 => value2,…],headerkey1 => value1,headerkey2 => value2, );
可以用来提交搜索等等,总之就是构造网址。
(4)$ua->mirror( $url, $filename ) 获取$url指定的文件,并按照$filename保存下来。
(5)$ua->request( $request )
$ua->request( $request, $content_file )
$ua->request( $request, $content_cb )
$ua->request( $request, $content_cb, $read_size_hint )
(6)$ua->simple_request( $request )
$ua->simple_request( $request, $content_file )
$ua->simple_request( $request, $content_cb )
$ua->simple_request( $request, $content_cb, $read_size_hint )
(7)$ua->is_protocol_supported( $scheme )

5、perl http模块总结
  perl发送http请求主要有 LWP,UserAgent, HTTP这些模块及其子模块组成
  (1)发送简单的http请求
  只需要使用LWP::Simple模块即可
  use LWP::Simple;
  $content = get(url); #返回得到的内容
  getstore(url, filename);#将目标url的内容保存到filename中
  head($url); 返回5个响应头($content_type, $document_length, $modified_time, $expires, $server)
  这个模块的方法只能做一些基本的http请求操作,比如只能发送get请求,获取不到响应的详细信息
  (2)发送通用的http请求
  这里用到3个主要的类
  LWP::UserAgent, HTTP::Request, HTTP::Response,
  需要注意的是 后面2个类继承HTTP::Headers和 HTTP::Message, HTTP::Headers 提供了添加请求头,获取响应头的方法。 HTTP::Message提供了content方法,对于request对象,如果request是post请求,则该方法会设置http的请求内容; 对于response对象该方法会返回http响应的内容
  标准的请求过程
  $response = $ua->request($request);
  在执行此方法之前可以对request对象进行设置, 方法执行完后
  可以从response对象中获取内容,响应头等
  UserAgent可以设置一些s全局选项, 比如timeout,max_redirect
  下面是一个完整的例子
  use LWP::UserAgent;
  use HTTP::Request;
  use HTTP::Response;
  $ua = LWP::UserAgent->new(timeout=>180);
  $request = HTTP::Request->new(‘POST’=$amp;>quot;$”);
  $request->content(‘age=18’);#post 请求参数
  $request->header(‘Accept-Language’, ‘zh-CN,zh;q=0.8’);
  $response = $ua->request($request);
  print $response->content();
  print $response->status_line();
  print $response->header(‘Content-Type’);
  总结:
  通过使用 LWP::UserAgent, HTTP::Request, HTTP::Response, 这三个类可以满足发起大多数http请求,

实例:

#perl test.pl

Can’t locate object method “new” via package “LWP::UserAgent” (perhaps you forgot to load “LWP::UserAgent”?) at ./test.pl line 532.

出错原因:没有引入”LWP::UserAgent”模块

解决方法:

# vim test.pl

use LWP::UserAgent;

参考文献:https://blog.csdn.net/herokoking/article/details/73089690

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,071
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,549
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,397
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,174
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,809
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,889