简体   繁体   English

phantomjs可以读取通过javascript设置的cookie吗?

[英]Can phantomjs read cookies set via javascript?

I am trying to use phantomjs to automate the process of login into facebook. 我正在尝试使用phantomjs自动化登录Facebook的过程。 The issue is that facebook uses js codes to set cookies before the login form is submitted. 问题在于,在提交登录表单之前,facebook使用js代码设置cookie。 Clicking on the email input box the login form can trigger the facebook js codes that set the cookies, so I created a script to click on the email box before login in, yet still I get the "Cookies are not enabled on your browser. Please enable cookies in your browser preferences to continue." 单击电子邮件输入框,登录表单可以触发设置cookie的facebook js代码,因此我创建了一个脚本,以在登录前单击电子邮件框,但是仍然出现“浏览器未启用Cookie。请在您的浏览器偏好设置中启用Cookie以继续。” message. 信息。 Here is my code: 这是我的代码:

var page = require('webpage').create();
var data = {};
var fs = require('fs');
var CookieJar = 'cookie.json';
page.customHeaders = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0'
};
if (fs.isFile(CookieJar)) {
    Array.prototype.forEach.call(JSON.parse(fs.read(CookieJar)), function(x) {
        phantom.addCookie(x);
    });
}
page.open('https://www.facebook.com/login.php', function(status) {
    setTimeout(function() {
        pageloaded();
        setTimeout(function() {
            afterclick();
        }, 3000);
    }, 3000);

    function pageloaded() {
        pagex = page.evaluate(function() {
            function mouseclick(element) {
                var event = document.createEvent(
                    'MouseEvents');
                event.initMouseEvent('click', true,
                    true, window, 1, 0, 0);
                element.dispatchEvent(event);
            }
            var element = document.querySelector('#email');
            mouseclick(element);
        });
    }

    function afterclick() {
        data.content = page.content;
        fs.write(CookieJar, JSON.stringify(phantom.cookies), 'w');
        console.log(page.content);
        phantom.exit();
    }
});

This code basically goes to the facebook login page then clicks on the email input box. 该代码基本上转到Facebook登录页面,然后单击电子邮件输入框。 The end result should be that the cookie.json file contains the cookies facebook has set, but I don't get any cookies. 最终结果应该是cookie.json文件包含facebook设置的cookie,但是我没有得到任何cookie。 I have also tried using the --cookies-file command line, seems to me that phantomjs can only store cookies set by the server side? 我也尝试过使用--cookies-file命令行,在我看来phantomjs只能存储服务器端设置的cookie? Or am i doing something wrong? 还是我做错了什么?

只需更改您的用户代理

page.settings.userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:44.0) Gecko/20100101 Firefox/44.0"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM