如何在多个NightmareJS实例中坚持并传递Cookie? 任何示例代码都会有所帮助。
答案 0 :(得分:3)
以下是如何使用从早期会话中保存的某些Cookie设置会话的示例。
// create a promise for retrieving cookies
function getCookies(url) {
return new Promise(function (resolve) {
Nightmare()
.goto(url)
.cookies.get() // get the cookies
.end()
.then(resolve)
});
}
var COOKIES;
getCookies(url).then(function (cookies) {
// save your cookies somewhere...
// you could save them in the file system (with NodeJs)
require('fs').writeFileSync(
'cookies.json',
JSON.stringify(cookies)
);
// or you could set a global variable
COOKIES = cookies;
})
// and now each time you want to use these cookies
// you would simply set them before each session
function google() {
return new Promise(function (resolve) {
Nightmare()
.goto('about:blank') // create your session by going to a blank page
.cookies.set(COOKIES) // or .cookies.set(require('fs').readFileSync('cookies.json'))
.goto('http://google.com')
// do your thing with the new cookies..
.end()
.then(resolve)
})
}