perl模块推荐21—UserAgent模拟HTTP上传文件

摘要

UserAgent通过模拟一切网页(HTTP)操作活动(GET POST PUT)等,从而实现自动化。在Perl 中两个比较有名的模块是LWP::UserAgent 和 Mojo::UserAgent。

Mojo 版本自动上传文件提交任务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/perl
use Mojo::UserAgent;
use Data::Dumper;
use Mojo::UserAgent::CookieJar;
my $ua = Mojo::UserAgent->new();
my $browser='Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.4.2.2000 Chrome/30.0.1599.101 Safari/537.36';

$ua->transactor->name($browser);
my $cookie_jar = $ua->cookie_jar;
$ua = $ua->cookie_jar(Mojo::UserAgent::CookieJar->new);

my $posturl="http://20xxxx9/upload_insert.php";


my @files=glob "DRN*";
print join "\n",@files;

foreach my $file(@files)
{
my $title=$file;
my $filename=$file;
upload_file($title,$filename);

}


sub upload_file
{
my ($title,$filename)=@_;
my $tx=$ua->post($posturl=>{Content_Type => 'form-data'}=>form=>{ task_title=>$title,
task_uploaded_file=>{file=>$filename}

} );
if (my $res = $tx->success)
{
print "OK\n";
}
else
{
my $err = $tx->error;
print "$filename failed\n";
die "$err->{code} response: $err->{message}" if $err->{code};
die "Connection error: $err->{message}";
}


}
LWP 版本自动上传文件提交任务
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/usr/bin/perl -w
use strict;
use LWP;


use HTTP::Request::Common qw( POST GET);

my $browser=LWP::UserAgent->new( cookie_jar=>{}); #非常重要

$browser->agent("MyApp/0.1 ");

my $req=POST(

'http://idtarget.rcas.sinica.edu.tw/step2.php',
[ jobname => 'benzfuran',
ligF => ['f:/test/benz_furan.mol2'], #这里是被上传的文件路径
email => '744891290@qq.com',
submit=>"1"
],
Content_Type => 'form-data', #这句不可少,表示类型为 multipart/form-data

'Host'=>'idtarget.rcas.sinica.edu.tw',

);


my $res = $browser->request($req);
print $res->code;

总结

利用这个模块可以模拟一切网页操作,从而可以实现爬虫、自动登陆、webqq等功能。
推荐灰灰的Mojo::webqq项目:
https://github.com/sjdy521/Mojo-Webqq