所以我正在使用 WWW::Mechanize
抓取网站。它工作得很好,除非我请求一个 url,例如:
http://www.levi.com/
我被重定向到:
http://us.levi.com/home/index.jsp
对于我的脚本,我需要知道这个重定向发生了,以及我被重定向到的 url 是什么。有没有办法用
WWW::Mechanize
检测到这一点?或 LWP
然后获取重定向的网址?谢谢!
最佳答案
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 的响应 header 。
关于Perl WWW::Mechanize(或 LWP)获取重定向 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10922054/