2017-02-02 30 views

回答

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) 
    }) 
} 
+0

'cookie.set(COOKIES)'不起作用我想因为它的一个对象或cookie而不是一个cookie,必须循环对吗? – 3zzy