gpt4 book ai didi

java - Selenium 优化 getVisibleElement(当元素不存在时)

转载 作者:搜寻专家 更新时间:2023-11-01 03:53:03 24 4
gpt4 key购买 nike

我正在使用 jBehave/Selenium 进行自动化测试。

现在我使用下面的代码获取页面上可见的元素;

public WebElement getVisibleElement( final By by, final WebElement parentElement, int timeoutValue, TimeUnit timeoutPeriod, int pollingInterval, TimeUnit pollingPeriod ) {
return fluentWait(timeoutValue, timeoutPeriod, pollingInterval, pollingPeriod).until( new Function<WebDriver, WebElement>(){
public WebElement apply(WebDriver driver) {
try{
WebElement element = parentElement.findElement(by);
if ( element.isDisplayed() ) {
return element;
} else {
return null;
}
} catch( NoSuchElementException e ) {}

return null;
}
} );
}

现在的问题是,如果该元素不在页面上,Selenium 会花费大量时间尝试在页面上找到它。有什么方法可以优化代码,使其在这种情况下不会花费很长时间?

最佳答案

甚至更优化的解决方案 - 是使用 findElements(locator).size()...

    /**
* Private method that acts as an arbiter of implicit timeouts of sorts.. sort of like a Wait For Ajax method.
*/
private WebElement waitForElement(By by) {
int attempts = 0;
int size = driver.findElements(by).size();

while (size == 0) {
size = driver.findElements(by).size();
if (attempts == MAX_ATTEMPTS) fail(String.format("Could not find %s after %d seconds",
by.toString(),
MAX_ATTEMPTS));
attempts++;
try {
Thread.sleep(1000); // sleep for 1 second.
} catch (Exception x) {
fail("Failed due to an exception during Thread.sleep!");
x.printStackTrace();
}
}

if (size > 1) System.err.println("WARN: There are more than 1 " + by.toString() + " 's!");

return driver.findElement(by);
}

它的构建方式是在对其进行操作之前调用它。类似的东西,

WebElement myElement = waitforElement(By.cssSelector("input#someInput"));
myElement.sendKeys("something");

这是一个经过验证的解决方案,我已经在生产级回归测试系统中进行了测试和积极使用。

关于java - Selenium 优化 getVisibleElement(当元素不存在时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19377825/

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