【问题标题】:Perl WWW::Mechanize (or LWP) get redirect urlPerl WWW::Mechanize(或 LWP)获取重定向 url
【发布时间】:2012-06-10 22:21:23
【问题描述】:

所以我使用WWW::Mechanize 来抓取网站。它工作得很好,除非我请求一个网址,例如:

http://www.levi.com/

我被重定向到:

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

对于我的脚本,我需要知道这个重定向发生了,以及我被重定向到的 url 是什么。有没有办法用WWW::MechanizeLWP 检测到这个,然后得到重定向的url?谢谢!

【问题讨论】:

    标签: perl url redirect www-mechanize lwp


    【解决方案1】:

    您也可以通过检查响应对象上的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() 返回的每个响应。

    【讨论】:

      【解决方案2】:
      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的响应头。

      【讨论】:

      • 如果我想再次允许重定向,或者像重置重定向计数,有没有办法可以做到这一点?或者例如,我是否可以按照一串重定向到他们的最终位置并且仍然知道状态在 300 到 400 之间?我摆脱了 max_redirect(0),但后来我得到了 500 的状态,我知道这是不对的......
      • 如果有人将其作为参考,只需在 $mech 中存储一个新的 WWW::Mechanize 对象即可。
      猜你喜欢
      • 2012-06-10
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多