Perl WWW::Mechanize(或 LWP)获取重定向 url [英] Perl WWW::Mechanize (or LWP) get redirect url

查看:78
本文介绍了Perl WWW::Mechanize(或 LWP)获取重定向 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我使用 WWW::Mechanize 来抓取网站.效果很好,除非我请求一个网址,例如:

So I am using WWW::Mechanize to crawl sites. It works great, except if I request a url such as:

http://www.levi.com/

我被重定向到:

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

对于我的脚本,我需要知道这个重定向发生了,以及我被重定向到的 url 是什么.无论如何,是否可以使用 WWW::MechanizeLWP 检测到这一点,然后获取重定向的 url?谢谢!

And for my script I need to know that this redirect took place and what the url I was redirected to is. Is there anyway to detect this with WWW::Mechanize or LWP and then get the redirected url? Thanks!

推荐答案

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 的响应标头.

If the status code is 3XX, then you should check response headers for redirection url.

这篇关于Perl WWW::Mechanize(或 LWP)获取重定向 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆