[英]Perl WWW::Mechanize (or LWP) get redirect url
所以我使用WWW::Mechanize
来抓取网站。 它工作得很好,除非我请求一个网址,例如:
http://www.levi.com/
我被重定向到:
http://us.levi.com/home/index.jsp
对于我的脚本,我需要知道这个重定向发生了,我被重定向的网址是什么。 无论如何使用WWW::Mechanize
或LWP
检测到这个,然后获取重定向的URL? 谢谢!
use strict;
use warnings;
use URI;
use WWW::Mechanize;
my $url = 'http://...';
my $mech = WWW::Mechanize->new(autocheck => 0);
$mech->max_redirect(0);
$mech->get($url);
my $status = $mech->status();
if (($status >= 300) && ($status < 400)) {
my $location = $mech->response()->header('Location');
if (defined $location) {
print "Redirected to $location\n";
$mech->get(URI->new_abs($location, $mech->base()));
}
}
如果状态代码是3XX ,那么您应该检查重定向URL的响应头。
您还可以通过检查响应对象上的redirects()
方法来到同一个地方。
use strict;
use warnings;
use feature qw( say );
use WWW::Mechanize;
my $ua = WWW::Mechanize->new;
my $res = $ua->get('http://metacpan.org');
my @redirects = $res->redirects;
say 'request uri: ' . $redirects[-1]->request->uri;
say 'location header: ' . $redirects[-1]->header('Location');
打印:
request uri: http://metacpan.org
location header: https://metacpan.org/
请参阅https://metacpan.org/pod/HTTP::Response# $ r-%3Eredirects请注意,多个重定向可能会将您带到当前位置。 因此,您可能希望检查通过redirects()
返回的每个响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.