如何打印正在设置的cookie / cookie_jar的值?
尝试:
##my $cookie_jar=HTTP::Cookies->new(file => "cookie.jar",autosave=>1,ignore_discard=>1);
my $cookie_jar=HTTP::Cookies->new(); ## Would like it to be in memory
my $agent = WWW::Mechanize->new(cookie_jar => $cookie_jar);
##my $agent = WWW::Mechanize->new();
##my $agent = WWW::Mechanize->new(autocheck => 1);
##$agent->cookie_jar( {} );
# we need cookies
##$agent->cookie_jar(HTTP::Cookies->new);
print "Set Cookie Jar?\n";
print $agent->cookie_jar->as_string();
print "\n";
$agent->get($url); // url is a https site
这些中没有太多运气,我做错了什么?
答案 0 :(得分:7)
嗯,你必须在饼干罐里放一些饼干才能看到输出中的任何饼干。到目前为止,你有一个空饼干罐。确保您添加一些cookie或您正在访问的站点设置它们:
use HTTP::Cookies;
use WWW::Mechanize;
my $cookie_jar = HTTP::Cookies->new;
my $agent = WWW::Mechanize->new( cookie_jar => $cookie_jar );
$cookie_jar->set_cookie(
qw(
3
cat
buster
/
.example.com
0
0
0
)
);
$agent->get( 'http://www.amazon.com' );
print "Set Cookie Jar?\n", $agent->cookie_jar->as_string, "\n";
这给了我输出:
Set Cookie Jar?
Set-Cookie3: session-id=000-0000000-0000000; path="/"; domain=.amazon.com; path_spec; discard; version=0
Set-Cookie3: session-id-time=1272524400l; path="/"; domain=.amazon.com; path_spec; discard; version=0 Set-Cookie3: cat=buster; path="/"; domain=.example.com; port=0; version=3
但是,您无需直接调用HTTP::Cookies
。 LWP
会照顾到这一点。您只需给cookie_jar
一个哈希引用:
my $agent = WWW::Mechanize->new( cookie_jar => {} );
如果您只想要来自特定响应的cookie,您可以创建一个单独的cookie jar来保存从响应中提取的cookie:
use WWW::Mechanize;
my $agent = WWW::Mechanize->new( cookie_jar => {} );
my $response = $agent->get( 'http://www.amazon.com' );
my $cookie_jar = HTTP::Cookies->new;
$cookie_jar->extract_cookies( $response );
print $cookie_jar->as_string;
答案 1 :(得分:2)
如果您要查找特定Cookie的值,则需要使用HTTP::Cookie's $cookie_jar->scan( \&callback )方法扫描整个Cookie jar。例如,要从www.linkedin.com获取JSESSIONID cookie,您可以使用以下代码:
#!/usr/bin/perl
use strict;
use warnings;
use LWP::UserAgent;
use HTTP::Cookies::Netscape;
my $cookies = HTTP::Cookies::Netscape->new(
hide_cookie2 => 1,
file => "$ENV{HOME}/.cookies.txt",
autosave => 1
);
my $browser = LWP::UserAgent->new(
env_proxy => 1,
autocheck => 1,
cookie_jar => $cookies,
agent => "get-jsessionid.pl/1.0"
);
$browser->env_proxy();
my $response = $browser->get( 'http://www.linkedin.com' );
if ($response->is_success)
{
$cookies->scan(sub
{
if ($_[1] eq 'JSESSIONID')
{
print "$_[1] @ $_[4] = $_[2]\n";
};
}
);
}
else
{
die $response->status_line;
}
输出类似于:
JSESSIONID @ www.linkedin.com =“ajax:11122233344455556667”
答案 2 :(得分:1)
您的主要问题似乎是您在实际访问网站之前尝试打印Cookie。请在致电get()