Selenium - 用类和文本搜索元素

时间:2015-01-15 22:54:03

标签: c# selenium timeout

我有以下代码将搜索具有给定className和text的元素,直到找到或超时。我不喜欢它在open循环中持续30秒而returnElement == null。有更有效的方法吗?注意:它无法仅根据文本找到元素。

    #region FindAndWaitForElementListWithClassAndText
    public static IWebElement FindAndWaitForElementWithClassAndText(IWebDriver driver, string className, string text, int timeout = 30)
    {
        if (driver == null)
            throw new ApplicationException("No Selenium Driver defined, cannot continue.");

        WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeout));
        IWebElement returnElement = null;

        wait.Until(a => driver.FindElements(By.ClassName(className)));

        //Starts task that times out after specified TIMEOUT_MILLIS
        var tokenSource = new CancellationTokenSource();
        CancellationToken token =  tokenSource.Token;
        var task = Task.Factory.StartNew(() => searchForElementWtihClassAndText(driver, className, text), token);
        if(!task.Wait(TIMEOUT_MILLIS, token))
        {
            LoggerHelper.ErrorFormat("Could not find element with class and text: {0} :: {1}", className, text);
            returnElement = null;
        }

        returnElement = task.Result;

        return returnElement;
    }
    #endregion

    private static IWebElement searchForElementWtihClassAndText(IWebDriver driver, String className, String text)
    {
        IWebElement returnElement = null;

        while (returnElement == null)
        {
            var theList = driver.FindElements(By.ClassName(className));
            if (theList != null && theList.Count > 0)
            {
                foreach (IWebElement el in theList)
                {
                    if (el.Text.Equals(text, StringComparison.OrdinalIgnoreCase))
                    {
                        returnElement = el;
                        LoggerHelper.InfoFormat("Found Class Name and Text: {0} / {1}", className, text);
                    }
                }
            }
        }
        return returnElement;
    }

这是一个示例元素:

<div class="smtListItem smtMessageItem">
    <!-- ngIf: message.SentItem -->
    <!-- ngIf: !message.SentItem -->
    <span class="smtListName ng-binding ng-
    scope" data-ng if=
    "!message.SentItem">user08&nbsp;EIGHT</span>
    <!-- end ngIf: !message.SentItem -->

    ...
</div>

1 个答案:

答案 0 :(得分:4)

您始终可以编写xpath来查找该元素,并检查该元素是否存在。

高级实现可能如下所示

public void Test()
{
    By @by = By.XPath("//span[contains(@class,'smtListName')][contains(text(),'lastname')]");

    try
    {
        new WebDriverWait(Driver, TimeSpan.FromSeconds(30)).Until(ExpectedConditions.ElementExists(@by));
    }
    catch (NoSuchElementException exception)
    {
        Console.WriteLine(exception.Message);
    }
}