首页 > 解决方案 > 如何在几秒钟内重试某些方法,当超时抛出方法的异常而不是 Selenium 中的 TimeoutException?

问题描述

我想制作一个选择元素来选择一个选项。但是页面加载时该选项可能不存在。因为选项是从数据库、API 或具有响应时间的东西加载的。

目前,我使用 selenium wait.until 和布尔条件。制作自定义等待方法。

我的解决方法:

                                                     .
                                                     .
                                                     .
String exceptionMessage;

public void myCode() throws Exception {
        exceptionMessage = "";
        Integer sec = 10;
        WebDriverWait wait = new WebDriverWait(shared.getBrowser(), Duration.ofSeconds(sec));
        try {
            wait.until(new ExpectedCondition<Boolean>() {
                public Boolean apply(WebDriver d) {
                    try {
                                                     .
                                                     .
                                                     .

                        CommonMethods.selectOption(element, optionText);
                        return true;
                    } catch (Exception e) {
                        exceptionMessage = e.getMessage();
                        return false;
                    }
                }
            });
        } catch (TimeoutException e) {
            throw new Exception("Timeout: [" + sec + "] seconds, Exception message: [" + exceptionMessage + "]");
        }
}

如果超时,结果将是:

java.lang.Exception: Timeout: [10] seconds, Exception message: [element not visible: Element is not currently visible and may not be manipulated

有硒方法吗?还是更好的方法?

标签: javaselenium

解决方案


WebDriverWait wait = new WebDriverWait(driver,30);
    wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(" xpath']")));        
      

使用唯一的 Xpath 来查找元素,因为会有一些隐藏的元素。

如果上述等待不起作用,您也可以尝试以下方法:

new WebDriverWait(Driver,TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementIsVisible("Yyour element path");

推荐阅读