我如何在多个 NightmareJS 实例中保留并传递 cookie? 任何示例代码都会有帮助。
最佳答案
以下示例展示了如何使用早期 session 中保存的一些 cookie 设置 session 。
// 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)
})
}
关于javascript - 在 NightmareJS 实例中保留 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42004406/