javascript - 在 NightmareJS 实例中保留 cookie

标签 javascript node.js web-scraping nightmare

我如何在多个 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/

相关文章:

java - HTML 抓取我拥有其身份验证详细信息的网站

javascript - 如何使用子域在其他域上注册服务 worker

javascript - 什么是\r"以及为什么要将它与\n 一起使用?

javascript - 日期验证 - 如何解决 Javascript 的自动更正日期问题?

javascript - NodeJs, Spawn 转换

javascript - Push Function To Array 将数组转换为数字

excel - 从带有 <li> 标签的网站中抓取 html 数据

javascript - Angularjs 多索引页面

javascript - WebRTC dataChannel.readyState 在 "connecting"上停止

rvest:选择并抓取特定(标题)字符串后的 html 表