2017-02-12 115 views
1
 

    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.set(),但這不起作用。NightmareJS:如何設置cookie?

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

+0

根據[這](https://github.com/segmentio/nightmare#cookiessetname-value)'cookies.set()'應該工作。 「這不起作用」是什麼意思?您是否嘗試在設置後立即獲取cookie,以便查看它是否有效? – Benni

+0

你能告訴我一些.cookies.set()和.cookies.get()的例子嗎? – happinapps

+0

好的,給我幾分鐘。 – Benni

回答

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

是的,它的工作原理。 但在我的例子中: 我使用.set('foo','bar')和.get(),然後授權。授權狀態是好的,我關閉過程 然後開始新的,我的狀態是未經授權的。我會嘗試在其他網站上進行此操作,並重復問題,我做錯了什麼。 可能在第二次迭代時不需要使用.set('foo','bar')? – happinapps

+0

NightmareJS不存儲你的cookies,你必須自己做。我會編輯我的回覆以滿足您的需求。 – Benni

+0

好吧,我明白了。謝謝! – happinapps