0

我试图通过读取浏览器 cookie(我之前使用 Firefox 登录创建的)来消除登录网站的过程。我使用这个Firefox 插件从 Firefox 导出它。它给出 200 OK 响应,但返回通用主页而不是我的自定义“登录”主页。如何确保将 cookie 正确传递到服务器?

#!/usr/bin/perl 
use strict ;
use warnings;
use LWP::UserAgent;
use HTTP::Cookies::Netscape;

my @GHeader    = (
                        'User-Agent'      => 'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.19) Gecko/2010040200 Ubuntu/8.04 (hardy) Firefox/3.0.19',
                        'Accept'          => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                        'Accept-Language' => 'en-us,en;q=0.5',                        
                        'Accept-Charset'  => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
                        'Accept-Encoding' => 'gzip,deflate',
                        'Keep-Alive'      => '300',
                        'Connection'      => 'keep-alive'
                  );

    my $cookie_jar = HTTP::Cookies::Netscape->new(
                          file => "cookies.txt",
                          );
    my $Browser = LWP::UserAgent->new;
    $Browser->cookie_jar( $cookie_jar );
    my ($OutLine,$response)=();    
    my  $URL = 'http://www.hanggliding.org/';
    printf("Get [%s]\n",$URL);
    $response = $Browser->get($URL,@GHeader);
    if($response->is_success)
    {
        if($response->status_line ne "200 OK")
        {
                printf("%s\n", $response->status_line);       
        }
        else
        {
            printf("%s\n", $response->status_line);                      
            $OutLine =$response->decoded_content;
            open(HTML,">out.html");printf HTML ("%s",$OutLine);close(HTML);
        }
    }
    else
    {
        printf("Failed to get url [%s]\n", $response->status_line);
    }  
4

1 回答 1

0

You can inject a handler to access or modify request/response data during processing.

Quoting LWP::UserAgent's docs:

Handlers are code that injected at various phases during the processing of requests. The following methods are provided to manage the active handlers:

$ua->add_handler( $phase => \&cb, %matchspec )

Add handler to be invoked in the given processing phase. For how to specify %matchspec see "Matching" in HTTP::Config.

...

request_send => sub { my($request, $ua, $h) = @_; ... }

This handler gets a chance of handling requests before they're sent to the protocol handlers. It should return an HTTP::Response object if it wishes to terminate the processing; otherwise it should return nothing.

From there, you can inject a handler which will analyze the request object, but otherwise do nothing:

use LWP::UserAgent;
use Data::Dumper;

sub dump_request {
    my ($request, $ua, $h) = @_;
    print Dumper($request);
    return undef;
}

my $browser = LWP::UserAgent->new;

$browser->add_handler(
    request_send => \&dump_request,
    m_method => 'GET'
);

$browser->get('http://www.google.com');
于 2013-08-14T17:54:01.720 回答