如何在perl中从cookie jar中获取会话id



我的问题很简单。。这是如何从cookie罐中获取会话id。。。我尝试过以下代码:-

use warnings;
use HTTP::Cookies;
use HTTP::Request::Common;
use LWP::UserAgent;
$ua = new LWP::UserAgent;
if ( !$ua ) {
    print "Can not get the page :UserAgent fialed n";
    return 0;
}
my $cookies = new HTTP::Cookies( file => './cookies.dat', autosave => 1 );
$ua->cookie_jar($cookies);
# push does all magic to exrtact cookies and add to header for further reqs. useragent should be newer
push @{ $ua->requests_redirectable }, 'POST';
$result = $ua->request(
    POST "URL",
    {   Username => 'admin',
        Password => 'admin',
        Submit   => 'Submit',
    }
);
my $session_id = $cookies->extract_cookies($result);
print $session_id->content;
print "nn";
$resp = $result->content;
#print "Result is nnn $resp n";
$anotherURI    = URL;
$requestObject = HTTP::Request::Common::GET $anotherURI;
$result        = $ua->request($requestObject);
$resp          = $result->content;
#print $resp."n";

我不知道会话id存储在哪里,以及如何获取它?注意:-URL包含页面的URL。

我写HTTP::CookieMonster是为了让这类事情变得更容易。如果你不知道你在寻找哪种饼干,你可以这样做:

use strict;
use warnings;
use HTTP::CookieMonster;
use WWW::Mechanize;
my $mech    = WWW::Mechanize->new;
my $monster = HTTP::CookieMonster->new( $mech->cookie_jar );
my $url = 'http://www.nytimes.com';
$mech->get( $url );
my @all_cookies = $monster->all_cookies;
foreach my $cookie ( @all_cookies ) {
    printf( "key: %s value: %sn", $cookie->key, $cookie->val);
}

如果你已经知道cookie的密钥,你可以这样做:

my $cookie = $monster->get_cookie('RMID');
my $session_id = $cookie->val;

查看HTTP::Cookies->scan。

像这样的东西应该会起作用(至少应该在域上添加一个约束):

my $session_id;
$cookie_jar->scan(
    sub {
        my ($key,       $val,    $path,    $domain,  $port,
            $path_spec, $secure, $expires, $discard, $hash
        ) = @_;
        if ( $key eq "session_id" ) {
            $session_id = $val;
        }
    }
);

最新更新