如何从Mojo中的文件加载cookie,就像这样的代码:
my $mech = WWW::Mechanize->new();
$mech->cookie_jar(HTTP::Cookies->new());
if (-e "cookie.txt") {
print q[Cookie file: cookie.txt found!n];
$mech->cookie_jar(HTTP::Cookies->new(
file => q[cookie.txt],
));
$mech->get(qq[$cfg->{'url'}/login]) or die qq[invalid requestn];
} else {
print q[Cookie file: cookie.txt NOT found!n];
$mech->get(qq[$cfg->{'url'}/login]) or die qq[invalid requestn];
$mech->submit_form(
form_name => 'login',
fields => {
'email' => $cfg->{'email'},
'password' => $cfg->{'password'},
},
);
die qq[ERROR: Failed to login!n] unless ($mech->success);
$mech->cookie_jar->save("cookie.txt");
}
除非有cookie.txt,否则脚本使用用户名和密码,并将生成的cookie保存在文件中的cookie中.txt并下次使用此文件。
我正在尝试在不使用 Mechanize 的情况下重写此代码,并且在保存和加载 cookie 文件时遇到问题。
my $ua = Mojo::UserAgent->new;
$ua->cookie_jar(Mojo::CookieJar->new);
and then I do not know how to continue :)
附言对不起我的英语和perl:)
据我所知,Mojolicious 不支持此功能,但您可以通过以下方式使用 Storable 模块的存储和检索功能:
use Mojo::Base -strict;
# uncomment to be sure
#BEGIN { $ENV{MOJO_USERAGENT_DEBUG} = 1; }
use Mojo::UserAgent;
use Storable;
my $cookie_path = 'my.cookie';
my $req_str = 'http://www.google.com/';
SAVE: {
my $ua1 = Mojo::UserAgent->new;
$ua1->get($req_str);
store $ua1->cookie_jar, $cookie_path;
}
my $ua2 = Mojo::UserAgent->new;
# load
$ua2->cookie_jar(retrieve($cookie_path));
# make a request with loaded cookie
$ua2->get($req_str);