【发布时间】:2018-05-11 15:40:31
【问题描述】:
我正在尝试使用 Perl 发送多个 HTTP 获取请求。我需要使用 sock 代理发送这些请求。
如果我使用以下代码,我可以使用 sock 代理发送请求
#!/usr/bin/perl
use strict;
use LWP::UserAgent;
my $ua = LWP::UserAgent->new(
agent => q{Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; YPC 3.2.0; .NET CLR 1.1.4322)},
);
$ua->proxy([qw/ http https /] => 'socks://localhost:9050'); # Tor proxy
#$ua->cookie_jar({});
$a = 10;
while ( $a < 20 ) {
my $rsp = $ua->get('http://example.com/type?parameter=1¶meter=2');
print $rsp->content;
$a = $a + 1;
}
它工作成功,但我需要使用AnyEvent 来并行发送多个 GET 请求
#!/usr/bin/perl
use strict;
use AnyEvent;
use AnyEvent::HTTP;
use Time::HiRes qw(time);
use LWP::Protocol::socks;
use AnyEvent::Socket;
my $cv = AnyEvent->condvar( cb => sub {
warn "done";
});
my $urls = [
"http://url-1-withallparameters",
"http://url-2-withallparameters",
"http://url-3-withallparameters",
];
my $start = time;
my $result;
$cv->begin(sub { shift->send($result) });
for my $url ( @$urls ) {
$cv->begin;
my $now = time;
my $request;
$request = http_request(
GET => $url,
timeout => 2, # seconds
sub {
my ($body, $hdr) = @_;
if ($hdr->{Status} =~ /^2/) {
push (@$result,
join("\t",
($url,
" has length ",
$hdr->{'content-length'},
" and loaded in ",
time - $now,
"ms"))
);
}
else {
push (@$result,
join("",
"Error for ",
$url,
": (",
$hdr->{Status},
") ",
$hdr->{Reason})
);
}
undef $request;
$cv->end;
}
);
}
$cv->end;
warn "End of loop\n";
my $foo = $cv->recv;
print join("\n", @$foo), "\n" if defined $foo;
print "Total elapsed time: ", time-$start, "ms\n";
这工作正常,但我无法使用 sock 代理发送这些请求。
即使在终端中,如果我导出像 curl 和 wget 这样的代理命令,它们也可以与 sock 代理一起正常工作,但是当我使用 Perl 命令将这个脚本作为 sock 代理执行时,它就不起作用了。
我可以将它与LWP::UserAgent 集成,但它不适用于AnyEvent。
我用过
proxy => [ $host, $port ],
下面
GET => $url,
但它仅适用于 HTTP 和 HTTPS 代理,不适用于 sock 代理。 这个url 适用于 HTTP/HTTPS 代理,但不适用于 sock 代理。
【问题讨论】:
-
不要使用
$a,它是sort的保留变量。 -
这对您有很大帮助,或者您可以建议一种方法,我可以像 AnyEvent 一样快地使用 sock 代理发送多个并行 http 请求。我不知道有任何其他模块可以像 AnyEvent 一样快地发送请求。
-
@Derek:已经有模块支持这一点。你看我的回答了吗?
-
是的,已经开始着手研究了。有人建议在现有模块中添加功能,所以我期待一个脚本,但评论被删除了。
-
Re "我不知道任何其他模块发送请求的速度和 AnyEvent 一样快。",LWP 很慢,完全是用 Perl 编写的。 Net::Curl 使用非常快的 libcurl 库。它甚至可以做并行请求(使用Net::Curl::Multi)。