问题
I have a Perl script that I run in Strawberry Perl in which I login to Facebook using WWW::Mechanize. For a short background, I use my script to automate an occasional "leaderboard" for a fun little game I invented to be played among my group of friends. I assign points based upon certain posts, and the objective is to earn the most points. Very simple. This script is complete, and it's worked for me in the past (I last ran it 4 days ago). However, I am unable to login to Facebook today. I dumped the content after the form submission to an HTML file, and it appears that I've returned back to the login screen with a red error box:
Cookies Required
Cookies are not enabled on your browser. Please enable cookies in your browser preferences to continue.
From what I understand, WWW::Mechanize features automatic cookies -- in other words by the default constructor, the bot should be accepting cookies. Cookies should be enabled by the browser. I should not see this screen, right?
I've read and experimented with WWW:Mechanize and HTTP::Cookies, but no matter what I try (fooling around with the cookie jar every which way), I cannot get past this "cookies required" error.
This is my code without any experimental fluff, very simple.
use WWW::Mechanize;
my $mech = WWW::Mechanize->new();
$mech->get("https://www.facebook.com/login.php");
$mech->submit_form(
fields => {
email => '<my email here>',
pass => '<my password here>',
}
);
open($out, ">", "output_page.html") or die "Can't open output_page.html: $!";
print $out $mech->content;
回答1:
Capture a session of you logging in with your browser (if you're using firefox you can use firebug, and check what HTTP headers are set - how-to. Set the same headers in your script, including the user agent. Check if the same cookies are set. You may end up with something like the below:
use strict;
use warnings;
use WWW::Mechanize;
use HTTP::Cookies;
my $cookie_jar = HTTP::Cookies->new(
hide_cookie2 => 1,
);
my $mech = WWW::Mechanize->new(
cookie_jar => $cookie_jar,
);
$mech->agent_alias('Windows Mozilla');
$mech->add_header( 'Connection' => 'keep-alive' );
$mech->add_header( 'Accept-Language' => 'en-GB,en;q=0.5' );
$mech->add_header( 'Accept-Encoding' => 'gzip, deflate' );
$mech->add_header( 'Accept' =>
'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' );
来源:https://stackoverflow.com/questions/31283839/facebook-login-via-perl-wwwmechanize-login-error-cookies-required