如何在C#Selenium中从IWebElement获取FindsByAttribute? [页面对象模型]

时间:2016-05-25 08:53:07

标签: c# selenium wait pageobjects

鉴于Selenium中的页面对象模型设计模式,我需要检查WebElement是否在页面上存在/启用/可点击,然后再对其执行操作。

基地' Page'类:

 public class Page
{            
    public Page()
    {
        PageFactory.InitElements(SeleniumTests.driver, this);
    }  
}

继承的类:

class Page_Certificate_ChooseOperator : Page
    {               
        [FindsBy(How = How.Id, Using = "SearchOperatorName")]
        public IWebElement txtName { get; set; }

        [FindsBy(How = How.Id, Using = "SearchOperatorEstablishmentNumber")]
        public IWebElement txtEstablishmentNumber { get; set; }

        [FindsBy(How = How.Id, Using = "searchButton")]
        public IWebElement btnSearch { get; set; }

        public void SelectOperator(String name, String establishmentNumber)
        {
            this.txtName.SetInputField(name);
            this.txtEstablishmentNumber.SetInputField(establishmentNumber);                
            this.btnSearch.SafeClick();
        }           
    }

最后是扩展方法的类:

 public static class SeleniumExtensionMethod
    {
        public static void SetInputField(this IWebElement webElement, String value)
        {
            webElement.Clear();
            webElement.SendKeys(value);
        }    

        public static void SafeClick(this IWebElement webElement, int timeout_in_seconds)
        {     
            //This is the difficult part. I need to check if the webElement is visible, but I don't want to write "low-level" code and specify the ID and  selector. Is there a way I can find out how the webElement was created by this class and say something like "webElement.How" to find "How.ID" or "webElement.Using" to find "btnSearch"? I need to use something like the below code using the PageObject
            // WebDriverWait wait = new WebDriverWait(SeleniumTests.driver, TimeSpan.FromSeconds(10));
            // IWebElement dynamicElement = wait.Until<IWebElement>(driver => driver.FindElement(By.Id("btnSearch")));  
            // dynamicElement.Click();

            //Now, I just use this, but it crashes on NoSuchElementFound since it goes too fast. I don't want to use ImplicitWait.
            btnSearch.Click();


        }
    }

我面临的挑战是,在点击按钮btnSearch之前我需要一个ExplicitWaity,因为它会抛出一个NoSuchElementFoundException。由于我使用[FindsBy]属性,我认为应该有一些方法来检查如何找到/创建webElement?我怎样才能做到这一点?或者我如何拥有整洁的代码并在页面对象上使用ExplicitWait?

1 个答案:

答案 0 :(得分:1)

要等待元素存在/启用/可点击,您可以使用ElementToBeClickable条件的服务员:

[FindsBy(How = How.Id, Using = "searchButton")]
public IWebElement btnSearch { get; set; }

public void SelectOperator(String name, String establishmentNumber)
{
    this.txtName.SetInputField(name);
    this.txtEstablishmentNumber.SetInputField(establishmentNumber);                

    new WebDriverWait(SeleniumTests.driver, TimeSpan.FromSeconds(10))
        .Until(ExpectedConditions.ElementToBeClickable(this.btnSearch))
        .Click();
}