如何使用 phantomjs 从文件中使用持久化 cookie [英] How can I use persisted cookies from a file using phantomjs

查看:30
本文介绍了如何使用 phantomjs 从文件中使用持久化 cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些身份验证才能访问特定的 url.在浏览器中,我只需要登录一次,至于其他可以使用 cookie 中的会话 id 的相关 url 不需要转到登录页面.同样,我可以在phantomjs的命令行中使用--cookies-file=cookies.txt在cookie文件中生成的cookie来打开需要相同cookie详细信息的其他页面.

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.

请提出建议.

推荐答案

Phantom JS 和 cookie

--cookies-file=cookies.txt 只会在 cookie jar 中存储非会话 cookie.登录和身份验证更常见的是基于会话 cookie.

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.

保存这些非常简单,但您应该考虑到它们可能很快就会过期.

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. 从 cookiejar 加载 cookie
  2. 点击一个 URL 来检查用户是否登录
  3. 如果没有登录

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

登录,将cookies保存到cookiejar

Log in, Save cookies to cookiejar

示例

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
 }


});

这篇关于如何使用 phantomjs 从文件中使用持久化 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆