I have a Perl script that uses WWW::Mechanize to read from a file and perform some automated tasks on a website. However, the website uses a 302 redirect after every time I request a certain page. I don't want to be redirected (the page that it redirects to takes too long to respond); I just want to loop through the file and call the first link over and over. I can't figure out how to make WWW::Mechanize NOT follow redirects. Any suggestions?
Asked
Active
Viewed 5,107 times
3 Answers
10
WWW::Mechanize
is a subclass of LWP::UserAgent
. So you can use any LWP::UserAgent
methods.
my $mech = WWW::Mechanize->new();
$mech->requests_redirectable([]);

Brad Gilbert
- 33,846
- 11
- 78
- 129

Alexandr Ciornii
- 7,346
- 1
- 25
- 29
5
WWW::Mechanize is a subclass of LWP::UserAgent; you can set the max_redirect or requests_redirectable options in the constructor as you would with LWP::UserAgent.

Wooble
- 87,717
- 12
- 108
- 131
-
I've tried setting the max_redirect to 0, but it didn't effect it. – rfusca May 22 '09 at 02:55
-
1If indeed max_redirect is not affecting whether or not LWP and Mech doesn't follow redirects, then that is a bug that should be reported. – Andy Lester Mar 31 '10 at 21:39
4
You can use $agent->max_redirect( 0 );, like in this example:
#!/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);
When running it prints:
Got HTTP/302 from http://www.depesz.com/test/redirect.
Got HTTP/200 from http://www.depesz.com/.
So, with max_redirect(0) - it clearly doesn't follow redirects.
-
Oddly enough, changing the max_redirect to 0 didn't work for me (I suspect it's a bug elsewhere in my code with that indirect effect since it SHOULD work), but changing requests_redirectable did work. – rfusca May 22 '09 at 12:03
-
1On another note...I use your depesz.com website all the time. Great resource for Postgres. – rfusca May 22 '09 at 12:06