问题描述
这是一个关于如何保持cookie从一个casperjs页面到另一个问题。
this is a question about how to persist cookies from one casperjs page to another..
所以基本上我有一个nodejs文件,产生casperjs作为一个工人某些任务..一个是登录,一旦登录我将cookie存储在一个文件中。
so basically i got a nodejs file that spawns casperjs as a worker to do certain tasks.. one is to login, once logged in I store the cookie in a file.
当我产生下一个casper worker ..我想它使用cookie,而不必再次登录..这两种方法失败 :
when i spawn the next casper worker.. i want it to to use the cookie rather having to login again.. both these methods failed:
第一:当我产生工作者capserjs时,我添加--cookies-file =。/ cookiefilename ie
var child = spawn('casperjs',['scrape.js',' - cookies-file =。/'+ cookieFileName]);
first: when i spawn the worker capserjs I add the --cookies-file=./cookiefilename ievar child = spawn('casperjs',['scrape.js','--cookies-file=./'+cookieFileName]);
第二在casperjs工作文件中..我使它从一个文件读取和设置cookie
second: within the casperjs worker file.. I make it read and set the cookie from a file ie
var casper = require('casper').create();
var cookieFileName = 'monsterCookie.txt';
// grab cookies from file
var fs = require('fs');
var utils = require('utils');
var cookies = fs.read(cookieFileName);
casper.page.setCookies(cookies);
casper.start('domain/page.html', function() {
//FAIL! cookies aren't used here
this.debugHTML();
});
casper.run();
注意:
- 之前),同样的情况发生在同一个casperjs页面对象中(请参阅)
- 请记住,我将cookie存储在文件中(即不存在任何json / cookie解析)..所以我的cookie文件看起来像这样
- it was mentioned earlier that
start
removes cookies from the page? if so how do I prevent that? - I know that sessions persist within the same phantomjs page object (see here https://gist.github.com/abbood/5347252) and same happens within the same casperjs page object (see here https://gist.github.com/abbood/5347287)
- keep in mind that I store cookies as is in the file (ie without any json/cookie parsing at all).. so my cookie file looks exactly like this
推荐答案
strong>
Saving cookies:
var fs = require('fs');
var cookies = JSON.stringify(phantom.cookies);
fs.write(cookieFilename, cookies, 644);
Cookie:
var fs = require('fs');
var data = fs.read(cookieFilename);
phantom.cookies = JSON.parse(data);
phantom
是PhantomJS中的全局变量。有关详情,请参阅
The phantom
is global variable in PhantomJS. More information you can get in wiki
这篇关于如何在不同的casperjs进程之间保留cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!