首页 > 解决方案 > 如何使用javascript刷新页面直到元素在硒中消失

问题描述

在 selenium JavaScript 中,我必须刷新页面,直到元素消失。由于它使用了 Promise,如果我使用 for 循环,即使满足条件,它也会创建许多 Promise,稍后它将被解决。由于某种原因,我还必须强制提供 driver.sleep(5000) 。

$browser.get("https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html").
then( function()
{
var p=Promise.resolve();
for (let index = 0; index < 5; index++) {    
    p = p.then(() => 
    isElementDisplayedAfterrefresh($driver.By.xpath("//span[text()='PouchDB']"), "input"))
    .then(a=>$browser.sleep(3000))
    .then(()=>$browser.navigate().refresh())
}
return p;
}
).then(
    ()=>console.log('done'))

如果元素没有显示,代码应该退出,如果元素仍然显示,它应该刷新。当我们不知道结果/迭代次数返回类型为 Promise 时,如何按顺序循环通过 Promise,如何打破循环?谢谢

编辑

https://gist.github.com/saiparth/045c32267e55b836f139bdac6597e57b 问题是它为循环安排命令,因此无论先前的索引是否有效,所有 5 次迭代都将执行。我也不应该使用 async/await

标签: javascriptseleniumpromise

解决方案


你怎么知道元素是否显示,如果我阅读正确,你似乎正在刷新页面? .then(a=>$browser.sleep(3000)) 不应该是这样的吗

.then((a => { if(a.isDisplayed() == true) { console.log('element displayed dont do anything') } 
  else { 
     $browser.sleep(3000))
    .then(()=>$browser.navigate().refresh())
}  }))

推荐阅读