c# - 如何使用运行时发生变化的 WebElement?

标签 c# selenium

我得到他的代码等待找到控件

WebDriverWait wait = new WebDriverWait(Browser, TimeSpan.FromSeconds(20));
var ok = wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.XPath("(//button[@id='btnOkDialog'])[" + buttonOccuranceNo + "]")));

当任何事件发生后在 dom 中进行某些控制时,我会使用它。

现在,如果我缩小页面中的搜索范围[就像在 WebDriver 中获取一个 div,它是一个 WebElement] 那么我如何在该范围内搜索任何控件,直到找到它或发生超时?

最佳答案

您需要设置不同的等待时间,使用 DefaultWait类:

var waitInnerScope = new DefaultWait<IWebElement>(divInsideWebDriver);
waitInnerScope.Timeout = TimeSpan.FromSeconds(timeout);
waitInnerScope.IgnoreExceptionTypes(typeof(NoSuchElementException));

然后与wait.Until一起使用:

var ok = waitInnerScope.Until(PresenceOfAllElementsLocatedBy(By.XPath("(//button[@id='btnOkDialog'])[" + buttonOccuranceNo + "]")));

编辑:自ExpectedConditions由实现 Func<IWebDriver, ...> 的静态方法组成用于 WebDriverWait , 你必须使用你自己的方法来获取 IWebElement这样:

public static Func<IWebElement, ReadOnlyCollection<IWebElement>> PresenceOfAllElementsLocatedBy(By locator)
{
    return (element) =>
    {
        try
        {
            var elements = element.FindElements(locator);
            return elements.Any() ? elements : null;
        }
        catch (StaleElementReferenceException)
        {
            return null;
        }
    };
}

或者您可以像这样对匿名方法使用 lambda 表达式:

waitInnerScope.Until<ReadOnlyCollection<IWebElement>>((element) => 
{
    try
    {
        var elements = element.FindElements(By.XPath("(//button[@id='btnOkDialog'])[" + buttonOccuranceNo + "]"));
        return elements.Any() ? elements : null;
    }
    catch (StaleElementReferenceException)
    {
        return null;
    }
});

关于c# - 如何使用运行时发生变化的 WebElement?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42038677/

相关文章:

C# ToString继承

java - 从在 Tomcat 中运行的 Servlet 使用 Selenium WebDriver 的方法

python - Selenium :WAITING元素可点击不工作

java - Selenium ChromeDriver : increasing time of getting WebElement Text

c# - 我如何定义单元测试的不同顺序?

c# - MVVM 和控件创建

c# - 使 SortedList 只读

c# - 如何为 ComboBox 中的文件列表启用自动完成

c# - 在另一个模型中利用模型方法和属性

selenium - 浏览器堆栈,用类或测试名称替换 session 名称