Selenium - 搜索带有 Class 和文本的元素

Selenium - Search for Element With Class and Text

我有以下代码将搜索具有给定类名和文本的元素,直到找到或超时。我不喜欢 returnElement == null 时它处于开环状态 30 秒的事实。有没有更有效的方法来做到这一点?注意:它不能仅根据文本找到元素。

    #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>

您可以随时编写 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);
    }
}