gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:52:17 24 4
gpt4 key购买 nike

我正在编写 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com