2016-11-09 26 views
3

我是Selenium的新手,之前使用Telerik免費測試框架。問題是我無法理解,如何使用已經與[FindsBy]標識的元素等待,檢查並單擊。如何使用硒元素等待,檢查,點擊沒有再次找到元素?

例如:

[FindsBySequence] 
    [FindsBy(How = How.Id, Using = "container-dimpanel")] 
    [FindsBy(How = How.CssSelector , Using = ".btn.btn-primary.pull-right")] 
    public IWebElement UpdateButton { get; set; } 

    internal void ClickUpdateButton(TimeSpan timeout) 
    { 
     new WebDriverWait(_driver, timeout). 
      Until(ExpectedConditions.ElementIsVisible(By.CssSelector(id)); 
     UpdateButton.Click(); 
    } 

我希望我的代碼,以等待更新按鈕是可見的,然後點擊它。但我想傳遞UpdateButton元素而不是使用By選擇器。

  • 不確定UpdateButton.Enabled是否等到其可見。

回答

2

有能見度接受一個WebElement預期的條件: https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html#visibilityOf-org.openqa.selenium.WebElement-

Until也返回所等待的元素,所以你可以合併成一條線這樣的:

internal void ClickUpdateButton(TimeSpan timeout) 
{ 
    WebDriverWait wait = new WebDriverWait(_driver, timeout); 
    wait.Until(ExpectedConditions.visibilityOf(UpdateButton)).click(); 
} 

然而在我的框架中,我通常會添加一個輔助函數來完成這個任務,因爲它的用處非常大。你也可以做類似的事情等到點擊等,並有接受WebElement或通過方法:

public WebElement waitThenClick(WebElement element) 
{ 
    WebDriverWait wait = new WebDriverWait(_driver, timeout); 
    return wait.Until(ExpectedConditions.visibilityOf(UpdateButton)).click(); 
} 
+0

感謝提供答案。不幸的是,C#在ExpectedConditions中沒有visibilityOf()方法。相反,它有ElementToBeClickable()。 –

+0

它看起來像圖書館有一個叫ElementIsVisible:https://seleniumhq.github.io/selenium/docs/api/dotnet/html/M_OpenQA_Selenium_Support_UI_ExpectedConditions_ElementIsVisible.htm – nofacade

1

C#的客戶端不具有一個內置的條件來檢查代理WebElement知名度。

此外預期的條件ExpectedConditions.ElementIsVisible檢查該元素被顯示,但不檢查該元素是從用戶的角度可見的。

所以最快和最可靠的方法是重試在服務員的點擊,直到成功:

Click(UpdateButton, 5); 
static void Click(IWebElement element, int timeout = 5) { 
    var wait = new DefaultWait<IWebElement>(element); 
    wait.IgnoreExceptionTypes(typeof(WebDriverException)); 
    wait.PollingInterval = TimeSpan.FromMilliseconds(10); 
    wait.Timeout = TimeSpan.FromSeconds(timeout); 
    wait.Until<bool>(drv => { 
     element.Click(); 
     return true; 
    }); 
} 
0

使用此功能,我寫來測試一個元素,你可以通過在名字。它會返回一個布爾值,並且你可以使用一個循環來等待這些元素出現。

static public bool verify(string elementName) 
{ 
    try 
    { 
     bool isElementDisplayed = driver.FindElement(By.XPath(elementName)).Displayed; 
     return true; 
    } 
    catch 
    { 
     return false; 
    } 
    return false; 
}