var Nightmare = require('nightmare'); var nightmare = Nightmare({ show: true }) nightmare .goto('https://mail.yandex.ru') .type('input[name=login]', 'mylogin') .type('input[name=passwd]', 'mypassword') .click('button.nb-button._nb-action-button.nb-group-start') .wait('.mail-User-Name') .cookies.get() .then(function (cookies) { //actions })
我在授权后获得了cookie,但我不知道我必须在哪里设置它们以及我必须如何设置它们。我一开始尝试.cookie.set()
,但这不起作用。
如何使用已保存的Cookie?感谢。
答案 0 :(得分:6)
我从节点终端做了以下事情:
> var Nightmare = require('nightmare')
undefined
> var nightmare = Nightmare({show:true})
undefined
> nightmare.
... goto('https://google.com').
... cookies.set('foo', 'bar').
... cookies.get().
... then((cookies) => {
... console.log(JSON.stringify(cookies, null, 4))
... })
Promise { <pending> }
> [
{
"name": "NID",
"value": "96=qo1qY9LTKh1np4OSgiyJTi7e79-_OIoIuc71hnrKWvN1JUnDLJqZlE8u2ij_4mW0-JJhWOCafo5J0j-YkZCFt8H2VHzYUom4cfEd2QLOEsHmAcT2ACx4a5xSvO0SZGZp",
"domain": ".google.de",
"hostOnly": false,
"path": "/",
"secure": false,
"httpOnly": true,
"session": false,
"expirationDate": 1502733434.077271
},
{
"name": "CONSENT",
"value": "WP.25d07b",
"domain": ".google.de",
"hostOnly": false,
"path": "/",
"secure": false,
"httpOnly": false,
"session": false,
"expirationDate": 2145916800.077329
},
{
"name": "foo",
"value": "bar",
"domain": "www.google.de",
"hostOnly": true,
"path": "/",
"secure": false,
"httpOnly": false,
"session": true
}
]
nightmare.cookies.set('key', 'value')
确实是使用它的正确方法,正如您在我的结果对象中看到的那样。也许https://mail.yandex.ru不接受您的Cookie,因为它无效。请执行相同操作并编辑您的问题以包含结果。
编辑:显然,OP需要存储Cookie,以便他可以在另一个梦魇实例中使用它们。这可以这样实现:
var Nightmare = require('nightmare')
var storedCookies // This is where we will store the cookies. It could be stored in a file or database to make it permanent
// First instance:
var nightmare1 = Nightmare({show: true})
nightmare1.
goto('https://google.com').
cookies.get().
then((cookies) => {
storedCookies = cookies
})
// Second instance:
var nightmare2 = Nightmare({show: true})
for(var i = 0; i < storedCookies.length; i++)
nightmare2.
cookies.set(storedCookies[i].name, storedCookies[i].value)
nightmare2.
goto('https://google.com')