Skip to main content
 首页 » 编程设计

c#之这是等待 selenium WebElement 的最佳方式吗

2024年01月24日28cyq1162

public static IWebElement FindElement(ExpectedConditions expectedConditions, By by, int timeoutInSeconds) 
{ 
    DefaultWait<IWebDriver> wait = new DefaultWait<IWebDriver>(driver); 
    wait.Timeout = TimeSpan.FromSeconds(timeoutInSeconds); 
    wait.PollingInterval = TimeSpan.FromMilliseconds(10000); 
    wait.IgnoreExceptionTypes(typeof(NoSuchElementException)); 
 
    IWebElement element = 
        wait.Until<IWebElement>(ExpectedConditions.ElementIsVisible(by)); 
} 

我的问题:

如何放置此 expectedConditions 而不是我方法中当前的内容?

我尝试改变:

    IWebElement element = 
        wait.Until<IWebElement>(ExpectedConditions.ElementIsVisible(by)); 

用这个:

    IWebElement element = 
        wait.Until<IWebElement>(expectedConditions(by)); 

并收到此错误:

Method name expected.

请您参考如下方法:

Until 方法需要一个谓词作为第一个参数。 谓词是一个定期调用的函数,直到它返回不同于 null 或 false 的内容。

所以在你的情况下你需要让它返回一个谓词而不是一个IWebElement:

public static Func<IWebDriver, IWebElement> MyCondition(By locator) { 
    return (driver) => { 
        try { 
            var ele = driver.FindElement(locator); 
            return ele.Displayed ? ele : null; 
        } catch (StaleElementReferenceException){ 
            return null; 
        } 
    }; 
} 
 
// usage 
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); 
IWebElement element1 = wait.Until(MyCondition(By.Id("..."))); 

等于:

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); 
IWebElement element = wait.Until(ExpectedConditions.ElementIsVisible(By.Id("..."))); 
element.Click(); 

你也可以使用 lambda 表达式

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); 
IWebElement element = wait.Until((driver) => { 
    try { 
        var ele = driver.FindElement(By.Id("...")); 
        return ele.Displayed ? ele : null; 
    } catch (StaleElementReferenceException){ 
        return null; 
    } 
}); 
element.Click(); 

或者扩展方法:

public static IWebElement WaitElementVisible(this IWebDriver driver, By by, int timeout = 10) { 
    return new WebDriverWait(driver, TimeSpan.FromSeconds(timeout)).Until((drv) => { 
        try { 
            var ele = drv.FindElement(by); 
            return ele.Displayed ? ele : null; 
        } catch (StaleElementReferenceException){  
            return null; 
        } catch (NotFoundException){  
            return null;  
        } 
    }); 
} 
 
 
// usage 
IWebElement element = driver.WaitElementVisible(By.Id("...")); 
element.Click(); 

如您所见,有很多方法可以等待元素处于特定状态。