PhantomJS / CasperJS网站登录,PhantomJS不接受cookie

时间:2012-11-21 12:02:47

标签: javascript login phantomjs casperjs

我最近尝试登录强制我接受cookie的网站。我正在使用phantomJs和casperJs。我写了一个应该处理登录的小脚本,但是它将我重定向到一个告诉我必须接受cookie的网站。电子邮件和密码只是占位符。

我要登录的网站是https://de.buyvip.com/。但我需要点击按钮Anmelden mit Amazon,这样我就可以使用我的亚马逊帐户登录了。其他登录表单不起作用。 (这导致了这个长网址,我只是从浏览器中复制了它)

有人可以帮助我吗?

这是脚本:

    var casper = require("casper").create()
    var fs = require('fs');
    var page = "https://www.amazon.de/ap/signin?openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&pageId=quarterdeckde&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&clientContext=280-1158662-4507036&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.mode=checkid_setup&marketPlaceId=A38GABX06X24K&openid.assoc_handle=quarterdeckde&openid.return_to=https%3A%2F%2Fde.buyvip.com%2Fsignin&openid.pape.max_auth_age=0&siteState=http%3A%2F%2Fde.buyvip.com%2Fhomepage%3Fhash%3DM";

    phantom.cookiesEnabled = true;

    casper.start(page, function()
    {
        console.log("started");
        this.fill('form#ap_signin_form', {
            'email' : 'myMail',
            'password' : 'myPass'
        }, true);
    });

casper.then(function()
{
    fs.write("test.html", this.getHTML(), "w");
});

    casper.run();

2 个答案:

答案 0 :(得分:24)

也许稍后,但这就是答案:

casper.userAgent('Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)');
由于亚马逊不喜欢默认的casper的用户代理,因为我的情况:“Mozilla / 5.0(Macintosh; Intel Mac OS X)AppleWebKit / 534.34(KHTML,像Gecko)CasperJS / 1.0.2 + Phantomjs / 1.7.0 Safari / 534.34“

答案 1 :(得分:3)

我的任务是制作将登录亚马逊网站的Phantom脚本。

如果您使用phantom.javascriptEnabled = true;运行Phantom并尝试使用usernamepassword登录Amazon,您将获得禁用JavaScript的消息,这意味着Javascript无法执行。如果未启用JS,则无法在Amazon上登录,因为cookie无法正常运行。

亚马逊执行小型JS代码以在登录前设置和删除cookie,这是源代码的一部分:

function setCookie(c_name,value,expiredays)
    {
        var exdate=new Date();
        exdate.setDate(exdate.getDate()+expiredays);
        document.cookie=c_name+ "=" +escape(value)+
            ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
    }

function checkCookieEnabled(nodeId)
        {
            setCookie('amznTest','1',null);
            if(getCookie('amznTest')){
                deleteCookie('amznTest');
            }else{
                document.getElementById(nodeId).style.display = 'block';
            }
        }
        checkCookieEnabled('message_warning');

经过数小时的解决方法后,您必须设置page.settings.javascriptEnabled = true;而不仅仅phantom.javascriptEnabled,一切顺利(对我而言)。

phantom对象启用javascript执行:

phantom.cookiesEnabled = true;

为您的page对象启用javascript执行(重要):

 var webPage = require('webpage');
    var page = webPage.create();
    page.settings.javascriptEnabled = true;
page.settings.userAgent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36';

现在,只需使用usernamepassword提交表单,即可登录。

UPDATE:

这是How to login Amazon using PhantomJS非常好的资源。相同的模式可用于登录任何其他网站。