【问题标题】:Asynchronicity issues with NightmareJSNightmareJS 的异步问题
【发布时间】:2017-01-09 14:24:20
【问题描述】:

我正在尝试使用 nightmarejs 构建一个脚本,该脚本可以一遍又一遍地单击一个按钮,例如 cmets 部分底部的那个 youtube 按钮,每次按下它时都会加载较旧的 cmets(例如:youtube .com/watch?v=pZISJqJbQuU&list=RDpZISJqJbQuU#t=3) 并在没有更多按钮可点击时停止。

我试过调用评估,只是为了首先调用 end() 方法并取消进程。我尝试使用 setTimeout 、 setInterval 和 then() 将循环转换为递归。每次由于 end() 的竞争条件,evaluate() 将完成它的工作但不退出(只是挂起)或在完成工作之前退出。

那里有经验丰富的 nightmarejs 用户吗?

    function youtube_button_clicker(group) {
    var nightmare = Nightmare({
        show: true
    });

    nightmare
        .goto(url)
        .inject('js', 'jquery-3.1.0.js')
        .then(
            () => nightmare.
         evaluate(function() {
    for (i=0;i>LEN;i++)
    { setTimeout(() => { $(button_element).click() }, i * 2000); }


    return "done"


}))
.catch(function (error) {

        console.error('Search failed:', error);
    });

}

删除 .end() 方法并挂起,再次放回 .end() 并跳过该过程 - 提前退出。我能做什么?

【问题讨论】:

  • 你的 setTimeouts 需要被包裹在 Promise 中,然后你需要 promise.all 它们,这样你会在所有完成后得到一个事件,然后你需要将 all 返回的 Promise 传递给 @987654325 @ 以便您可以将其与另一个 thenend 正确链接
  • 你能给我看一个代码示例吗?

标签: javascript node.js phantomjs browser-automation nightmare


【解决方案1】:

.evaluate() 函数不能是异步的,至少在包含#819(或类似的东西)之前不能。换句话说,用setTimeout() 评估是行不通的。此外,我认为在这种情况下这不是一个特别好的方法,即使它可以开箱即用。

顺便说一句,你可能想去阅读nightmare-examples 中的this 示例。它简要介绍了链接多个操作和循环。

您可能可以使用递归函数,但您必须小心强制执行停止条件。 (你可能还想看看#625,动作是滚动的,但问题是相似的。)从臀部来看,我认为这样的事情可能会让你接近:

var iterations = 0;
var reclick = function(nm) {
  return nm
    .click('#some-button')
    .wait('#element-you-check-for')
    .then(function() {
      // you could also use `.visible()` or something before this `.then()`
      // depends on your use case
      // here, I'm using the number of iterations
      if (iterations++ < 10) {
        return reclick(nm);
      }
      return;
    });
}

nightmare
  .goto('http://my-domain.tld')
  .then(function() {
    return reclick(nightmare);
  })
  .then(function(){
    // ... other actions
  })

【讨论】:

    猜你喜欢
    • 2018-10-03
    • 2023-03-26
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    • 2010-12-16
    相关资源
    最近更新 更多