Perl的WWW ::机械化(或LWP)得到重定向URL(Perl WWW::Mechanize (

2019-06-25 06:46发布

所以我使用WWW::Mechanize抓取网站。 它的伟大工程,但如果我一个网址,例如:

http://www.levi.com/

我重定向到:

http://us.levi.com/home/index.jsp

而对于我的剧本,我需要知道,这重定向发生了什么,我重定向到URL是。 反正是有与检测到这种WWW::MechanizeLWP ,然后得到重定向的URL? 谢谢!

Answer 1:

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。



Answer 2:

您也可以通过检查到达同一个地方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()



文章来源: Perl WWW::Mechanize (or LWP) get redirect url