Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
626 views
in Technique[技术] by (71.8m points)

authentication - How can I use persisted cookies from a file using phantomjs

I have some authentication requried to hit a particular url. In browser I need to login only once, as for other related urls which can use the session id from the cookie need not required to go to the login page. Similarly, can I use the cookie generated in the cookie file using --cookies-file=cookies.txt in the commandline in phantomjs to open other page which requires the same cookie detail.

Please suggest.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Phantom JS and cookies

--cookies-file=cookies.txt will only store non-session cookies in the cookie jar. Login and authentication is more commonly based on session cookies.

What about session cookies?

To save these is quite simple, but you should consider that they will likely expire quickly.

You need to write your program logic to consider this. For example

  1. Load cookies from the cookiejar
  2. Hit a URL to check if the user is logged in
  3. If not logged in

    Log in, Save cookies to cookiejar

  4. continue with processing

Example

var fs = require('fs');
var CookieJar = "cookiejar.json";
var pageResponses = {};
page.onResourceReceived = function(response) {
    pageResponses[response.url] = response.status;
    fs.write(CookieJar, JSON.stringify(phantom.cookies), "w");
};
if(fs.isFile(CookieJar))
    Array.prototype.forEach.call(JSON.parse(fs.read(CookieJar)), function(x){
        phantom.addCookie(x);
    });

page.open(LoginCheckURL, function(status){
 // this assumes that when you are not logged in, the server replies with a 303
 if(pageResponses[LoginCheckURL] == 303)
 {  
    //attempt login
    //assuming a resourceRequested event is fired the cookies will be written to the jar and on your next load of the script they will be found and used
 }


});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...