2016-04-16 17 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)); 
} 

私の質問:代わりに私の方法では、現在あるもののこのexpectedConditionsを置く方法これは、セレニウムWebElementを待つ最善の方法ですか?

私は変更しよう:

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

そして、このエラー受信:これで

IWebElement element = 
     wait.Until<IWebElement>(ExpectedConditions.ElementIsVisible(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(); 

ご覧のとおり、要素が特定の状態であるのを待つ方法はたくさんあります。

関連する問題