Aru*_*run 24 authentication automation phantomjs
我需要一些身份验证才能获得特定网址.在浏览器中我只需要登录一次,因为可以使用cookie中的会话ID的其他相关URL不需要转到登录页面.同样,我可以--cookies-file=cookies.txt在phantomjs的命令行中使用cookie文件中生成的cookie 来打开需要相同cookie细节的其他页面.
请建议.
Jas*_*son 28
--cookies-file=cookies.txt只会在cookie jar中存储非会话cookie.登录和身份验证通常基于会话cookie.
保存这些非常简单,但您应该考虑它们可能会很快过期.
您需要编写程序逻辑来考虑这一点.例如
如果没有登录
登录,将cookie保存到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
}
});
Run Code Online (Sandbox Code Playgroud)
该选项创建的文件--cookies-file=cookies.txt是从CookieJar序列化的:有多余的字符,有时难以解析.
它可能看起来像:
[General]
cookies="@Variant(\0\0\0\x7f\0\0\0\x16QList<QNetworkCookie>\0\0\0\0\x1\0\0\0\v\0\0\0{__cfduid=da7fda1ef6dd8b38450c6ad5632...
Run Code Online (Sandbox Code Playgroud)
我过去使用过phantom.cookies.此数组将由存储在PhantomJS启动配置/命令行选项中指定的cookie文件中的任何现有Cookie数据预先填充(如果有).但您也可以使用phantom.addCookie添加动态cookie .
一个基本的例子是
phantom.addCookie({
'name': 'Valid-Cookie-Name', /* required property */
'value': 'Valid-Cookie-Value', /* required property */
'domain': 'localhost', /* required property */
'path': '/foo',
'httponly': true,
'secure': false,
'expires': (new Date()).getTime() + (1000 * 60 * 60) /* <-- expires in 1 hour */
});
Run Code Online (Sandbox Code Playgroud)
使用这些方法,实现自己的cookie管理逻辑并不困难.
| 归档时间: |
|
| 查看次数: |
21017 次 |
| 最近记录: |