2009-05-21 104 views
11

我有一个Perl脚本,它使用WWW::Mechanize从文件读取并在网站上执行一些自动化任务。但是,每次请求某个页面后,该网站都会使用302重定向。我不想被重定向(它重定向的页面需要很长时间才能响应);我只想遍历文件并反复调用第一个链接。我无法弄清楚如何使WWW :: Mechanize不遵循重定向。有什么建议么?如何让WWW :: Mechanize避免重定向?

回答

5

WWW :: Mechanize是LWP :: UserAgent的子类;您可以像使用LWP :: UserAgent一样在构造函数中设置max_redirect或requests_redirectable选项。

+0

我试着将max_redirect设置为0,但它没有影响它。 – rfusca 2009-05-22 02:55:29

+1

如果确实max_redirect不影响LWP和Mech是否不遵循重定向,那么这是一个应该报告的错误。 – 2010-03-31 21:39:46

4

您可以使用$代理 - > max_redirect(0);,就像这个例子:

#!/usr/bin/perl -w 
use strict; 

use WWW::Mechanize; 

my $agent = WWW::Mechanize->new('autocheck' => 1, 'onerror' => undef,); 
$agent->max_redirect(0); 
$agent->get('http://www.depesz.com/test/redirect'); 
printf("Got HTTP/%s from %s.\n", $agent->response->code, $agent->uri); 

$agent->max_redirect(1); 
$agent->get('http://www.depesz.com/test/redirect'); 
printf("Got HTTP/%s from %s.\n", $agent->response->code, $agent->uri); 

在运行时它打印:

Got HTTP/302 from http://www.depesz.com/test/redirect. 
Got HTTP/200 from http://www.depesz.com/. 

所以,用max_redirect(0) - 它显然不遵循重定向。