How to get Cookies?
Using the WWW::Mechanize and HTTP::Cookies how would I extract the cookie past in the response from the server?
#usr/bin/perl
#MagicLogin.pl
use warnings;
use strict;
use Win32::IE::Mechanize;
use HTTP::Message;
use WWW::Mechanize;
use HTTP::Request::Form;
use HTML::TreeBuilder 3.0;
my $url = 'http://magic.dstcorp.net/MagicDST/';
my $mech = WWW::Mechanize->new(cookie_jar => {});
$mech->agent_alias('Windows IE 6');
my $cookie_jar = new HTTP::Cookies;
my $res = $mech->get($url);
my $tree = new HTML::TreeBuilder;
$tree->parse($res->content);
$tree->eof;
my @forms = $tree->find_by_tag_name('form') or die "No form available";
my $f = HTTP::Request::Form->new($forms[0], $url);
my @fields = $f->allfields;
my $name = $f->name;
my $links = $f->link;
my $buttons = $f->buttons;
my $referrer = $f->referer;
print "Name: ", $name, "\nLink: ", $links, "\nFields: ", @fields,"\nButtons: ", $buttons, "\nReferrer: ", $referrer;
my $response = $mech->request($f->press("ok"));
my $cookie = $cookie_jar->extract_cookies($response);
print $response->content if $response->is_success;
print "Succesfully got url" if $mech->success;
#my $headers开发者_运维知识库 = new HTTP::Headers;
#my $cookie = $headers->header('Cookie:');
#print "Cookie:", $headers->referer;
#$mech->get($url);
#my @forms = $mech->forms;
#my $content = $mech->content;
my $output_content = 'MagicLogin.html';
#open Write ,">$output_content";
#print Write $content;
Output:
Name: frmLoginEmbedded
Use of uninitialized value $link in print at MagicLoginTest.pl line32. Link:Fields: Buttons: 0 Use of uninitialized value $referre in print at MagicLoginTest.pl line 37.
Thanks in advance for the help.
Mechanize already includes a cookie jar. You need not construct it manually.
use Data::Dumper qw(Dumper);
use WWW::Mechanize qw();
my $m = WWW::Mechanize->new;
$m->get(…);
$m->cookie_jar; # returns a HTTP::Cookies object
# e.g.
print $m->cookie_jar->as_string;
$m->cookie_jar->scan(sub { print Dumper \@_; })
I use the following snippet to access cookies:
my $jar = HTTP::Cookies->new();
my $mech = WWW::Mechanize->new(cookie_jar => $jar);
$mech->get('http://www.example.com');
# $jar now contains any cookies set during the GET
print $jar->as_string(), "\n";
精彩评论