如何在浏览器范围中设置全局变量.wait(fn)NightmareJS

时间:2017-10-26 19:58:32

标签: javascript node.js nightmare

我想根据我正在抓取的网页设置一个全局变量。但是,我只能用.evaluate和.then来做到这一点。这不是我需要的,因为在那之后我无法运行任何东西。

感谢您的帮助! :)

var global;

nightmare
.goto(url)
.wait(() => {
  global = document.getElementById("element").textContent;
})
.click()
.wait()
.more...

2 个答案:

答案 0 :(得分:0)

人们会告诉你不要用全局变量做事。我想你只想在一些小脚本中存储和使用一些数据。有几种方法可以保存变量供以后使用。我现在不会通过数据库和类似的东西。

梦魇实例中的

Window对象

您可以使用窗口对象,因为只要您是同一页面并且不刷新页面就会存在窗口对象。

await nightmare
.goto(url)
.evaluate(() => {
  window.aGlobalVariable = document.getElementById("element").textContent;
})

然后,只要您在同一页面,就可以稍后调用它。

await nightmare
.evaluate(() => {
  console.log(`${aGlobalVariable} looks tasty`);
})

在上下文之间保存并传递变量

let aGlobalVariable;
aGlobalVariable = await nightmare
.goto(url)
.evaluate(() => {
  return document.getElementById("element").textContent;
})

现在您可以从nodeJS上下文访问aGlobalVariable。 无论何时你想在梦魇中再次使用它,你都可以再次将它传递给浏览器。

await nightmare
.goto(url)
.evaluate((aGlobalVariable) => { // <-- call it in the function
  console.log(`${aGlobalVariable} looks tasty.`)
}, aGlobalVariable) // <-- pass it here

确保您了解异步等待和承诺,否则在运行这些代码时最终会出现奇怪的错误。

以下是一些参考资料。

答案 1 :(得分:0)

您可以设置全局变量并在评估函数中访问它们

const p1 = 1;
const  p2 = 2;

nightmare
  .evaluate(
    function (param1, param2) {
      //now we're executing inside the browser scope.
      return param1 + param2;
    },
    p1,
    p2 
  )
  .end();