2016-04-16 1 views
1
public static IWebElement FindElement(ExpectedConditions expectedConditions, By by, int timeoutInSeconds) 
{ 
    DefaultWait<IWebDriver> wait = new DefaultWait<IWebDriver>(driver); 
    wait.Timeout = TimeSpan.FromSeconds(timeoutInSeconds); 
    wait.PollingInterval = TimeSpan.FromMilliseconds(10000); 
    wait.IgnoreExceptionTypes(typeof(NoSuchElementException)); 

    IWebElement element = 
     wait.Until<IWebElement>(ExpectedConditions.ElementIsVisible(by)); 
} 

Мои вопросы:Разве это лучший способ подождать селена WebElement?

Как поставить этот expectedConditions вместо того, что в настоящее время в моем методе?

я пытаюсь изменить:

IWebElement element = 
     wait.Until<IWebElement>(ExpectedConditions.ElementIsVisible(by)); 

с этим:

IWebElement element = 
     wait.Until<IWebElement>(expectedConditions(by)); 

И получил эту ошибку:

Method name expected.

ответ

4

Пока метод не требует предикат в качестве первого аргумента. Предикат - это функция, которая вызывается в регулярном интервале, пока не вернется что-то отличное от null или false.

Так что в вашем случае вам нужно, чтобы сделать его возвращать предикат, а не IWebElement:

public static Func<IWebDriver, IWebElement> MyCondition(By locator) { 
    return (driver) => { 
     try { 
      var ele = driver.FindElement(locator); 
      return ele.Displayed ? ele : null; 
     } catch (StaleElementReferenceException){ 
      return null; 
     } 
    }; 
} 

// usage 
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); 
IWebElement element1 = wait.Until(MyCondition(By.Id("..."))); 

Что равно:

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); 
IWebElement element = wait.Until(ExpectedConditions.ElementIsVisible(By.Id("..."))); 
element.Click(); 

Вы можете также использовать лямбда-выражение

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); 
IWebElement element = wait.Until((driver) => { 
    try { 
     var ele = driver.FindElement(By.Id("...")); 
     return ele.Displayed ? ele : null; 
    } catch (StaleElementReferenceException){ 
     return null; 
    } 
}); 
element.Click(); 

или способ продления:

public static IWebElement WaitElementVisible(this IWebDriver driver, By by, int timeout = 10) { 
    return new WebDriverWait(driver, TimeSpan.FromSeconds(timeout)).Until((drv) => { 
     try { 
      var ele = drv.FindElement(by); 
      return ele.Displayed ? ele : null; 
     } catch (StaleElementReferenceException){ 
      return null; 
     } catch (NotFoundException){ 
      return null; 
     } 
    }); 
} 


// usage 
IWebElement element = driver.WaitElementVisible(By.Id("...")); 
element.Click(); 

Как вы видите, существует много способов подождать, пока элемент будет определенным состоянием.

Смежные вопросы