How can I get the final URL without getting the page using Perl and LWP?

I am making a web scraper using Perl LWP. I need to process a set of URLs, some of which can redirect (1 or more times).

How can I get the final URL with all redirects allowed using the HEAD method?

+5
source share
2 answers

If you are using the fully functional version of LWP :: UserAgent , then the response that is returned is an instance of HTTP :: Response , which in turn has the HTTP :: Request attribute . Note that this is NOT necessarily the same HTTP :: Request that you created with the source URL in your set of URLs, as described in the HTTP :: Response documentation for how to get the request instance in the response instance:

$ r-> request ($ request)

This is used to get / set the request attribute. The request attribute is the link to the request that caused this response. It should not be the same request passed to the $ ua-> request () method, because between them there could be repeated redirection and authorization attempts.

, uri URI. , URI .

Perl script, , , :

#!/usr/bin/perl

use strict;
use warnings;

use LWP::UserAgent;

my $ua;  # Instance of LWP::UserAgent
my $req; # Instance of (original) request
my $res; # Instance of HTTP::Response returned via request method

$ua = LWP::UserAgent->new;
$ua->agent("$0/0.1 " . $ua->agent);

$req = HTTP::Request->new(HEAD => 'http://www.ecu.edu/wllc');
$req->header('Accept' => 'text/html');

$res = $ua->request($req);

if ($res->is_success) {
    # Using double method invocation, prob. want to do testing of
    # whether res is defined.
    # This is inline version of
    # my $finalrequest = $res->request(); 
    # print "Final URL = " . $finalrequest->url() . "\n";
    print "Final URI = " . $res->request()->uri() . "\n";
} else {
    print "Error: " . $res->status_line . "\n";
}
+11

perldoc LWP:: UserAgent, GET HEAD:

$ua = LWP::UserAgent->new( %options )

...
       KEY                     DEFAULT
       -----------             --------------------
       max_redirect            7
       ...
       requests_redirectable   ['GET', 'HEAD']

:

#!/usr/bin/perl

use strict; use warnings;
use LWP::UserAgent;

my $ua = LWP::UserAgent->new();
$ua->show_progress(1);

my $response = $ua->head('http://unur.com/');

if ( $response->is_success ) {
    print $response->request->uri->as_string, "\n";
}

:

** HEAD http://unur.com/ ==> 301 Moved Permanently (1s)
** HEAD http://www.unur.com/ ==> 200 OK
http://www.unur.com/
+8

All Articles