NightmareJS:如何设置cookie?


      var Nightmare =要求('噩梦');
      var nightmare =噩梦({
         显示:真的
      })


     恶梦
        .goto( 'https://mail.yandex.ru')
        .type('input [name = login]','mylogin')
        .type('input [name = passwd]','mypassword')
        。点击( 'button.nb-button._nb  - 动作 -  button.nb基团的启动')
        .wait(“邮件的用户名”)
        .cookies.get()
        。然后(函数(cookies){
          //行动
        })

我得到授权后得到cookies,但我不知道我必须在哪里设置它们,以及如何设置它们。 我已经尝试在开始时执行.cookie.set() ,但这不起作用。

我如何使用保存的cookie? 谢谢。

我从节点terminal执行了以下操作:

 > 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,因为它是无效的&#x3002; 请执行相同的操作并编辑您的问题以包含您的结果。

编辑:显然,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')