selenium - 在 Protractor 中选择第一个可见元素

标签 selenium protractor

我正在编写 Protractor 测试并喜欢它,尽管有时似乎会陷入一些似乎应该很简单的事情。例如,我想遍历其中一个页面上包含“提名”文本的所有按钮。页面上有几十个,但只有 1 或 2 个可见。所以我想点击第一个。这是我目前使用的代码:

    var nominateButtons = element.all(by.buttonText('Nominate'));
    nominateButtons.then(function(els){
        for(var x = 0;x < els.length;x++){
            //Since isDisplayed returns a promise, I need to do it this way to get to the actual value
            els[x].isDisplayed().then(function(isVisible){
                //isVisible now has the right value                 
                if(isVisible){
                    //But now els is not defined because of the scope of the promise!!
                    els[x].click();
                }
            });
        }
    });

当我运行此代码时,出现“无法调用未定义的方法单击”错误,因为 els[x] 不再在范围内,但我似乎无法在不使用 promise 的情况下检查可见性。所以我的问题是,如何遍历元素集合,检查它们的可见性,然后单击第一个可见的元素? (我尽量不使用期望来检查可见性,因为我知道大多数按钮都不可见)

提前致谢

最佳答案

els被定义。未定义的是 x .
最简单的方法是:

var nominateButtons = element.all(by.buttonText('Nominate'));
var displayedButtons = nominateButtons.filter(function(elem) {
   return elem.isDisplayed(); 
});
displayedButtons.first().click();


element.all(by.buttonText('Nominate')).
  filter(function(elem) {
    return elem.isDisplayed(); 
  }).
  first().
  click();

编辑,顺便说一句,您不应该依赖此行为(单击文本“提名”的第一个按钮),因为它会在您更改应用程序时导致问题。看看您是否可以按 ID 选择,或者选择更具体的“提名”,例如 element(by.css('the section the nominate is under')).element(by.buttonText('Nominate'));
再次编辑:见 Using protractor with loops解释

关于selenium - 在 Protractor 中选择第一个可见元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27905584/

相关文章:

javascript - 检查模态是否打开时出现 NoSuchElementError

javascript - 使用 Protractor 移动鼠标

javascript - 将 Protractor 测试脚本和依赖项打包到一个文件中

java - 如何减少 Gecko 驱动程序日志的详细程度?

python - selenium测试密码如何加解密?

python - 将扩展与 Google Chrome Selenium 驱动程序一起使用

java - 使用 PageFactory.initElements 在父类中初始化子类 Web 元素

javascript - 单击未定义数量的对话框

angularjs - Protractor :在更新期间测试多个用户登录是否存在冲突

java - 下拉列表不选择可见时的值