我正在努力解决的原因是为什么LWP :: UserAgent不提供访问器,以便我可以通过提供cookie的名称来获取我想知道的关于cookie_jar中的cookie的所有内容。我意识到cookie_jar上有scan()方法,但是为一些基本的东西提供回调似乎需要很多开销。这就是我现在所拥有的:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dump qw (dump);
use WWW::Mechanize;
my $mech = WWW::Mechanize->new;
$mech->get( 'http://www.nytimes.com' );
my %cookies = ();
$mech->cookie_jar->scan( \&check_cookies );
dump \%cookies;
sub check_cookies {
my @args = @_;
$cookies{ $args[1] } = {
version => $args[0],
val => $args[2],
path => $args[3],
domain => $args[4],
port => $args[5],
path_spec => $args[6],
secure => $args[7],
expires => $args[8],
discard => $args[9],
hash => $args[10],
};
}
脚本的输出是这样的:
{ adxcs => {
discard => 1,
domain => ".nytimes.com",
expires => undef,
hash => {},
path => "/",
path_spec => 1,
port => undef,
secure => undef,
val => "-",
version => 0,
},
RMID => {
discard => undef,
domain => ".nytimes.com",
expires => 1374340257,
hash => {},
path => "/",
path_spec => 1,
port => undef,
secure => undef,
val => "02b4bc821c00500991212ba2",
version => 0,
},
}
所以,这让我可以通过名称轻松访问cookie,但我想知道是否有更简单的方法来执行此操作,或者是否有一个我不知道的有用模块。
答案 0 :(得分:0)
$cookies->scan(sub
{
if ($_[1] eq $name)
{
print "$_[1] @ $_[4] = $_[2]\n";
};
});
输出将是例如:
sessionID @ www.nytimes.com = 1234567890
修改:>>
sub getCookieValue
{
my $cookies = $_[0];
my $name = $_[1];
my $result = null;
$cookies->scan(sub
{
if ($_[1] eq $name)
{
$result = $_[2];
};
});
return $result;
}
并像这样使用它:
print getCookieValue($cokies, 'sessionID');