.net OpenQASelenium 等待常见的处理方式

.net Selenium 等待常见的处理方式

显示等待

1使用Until和匿名函数的方法

var wait = new WebDriverWait(driver, new TimeSpan(0, 0, 30));
wait.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(ElementNotVisibleException));
var element = wait.Until(() =>
{
    var e = Driver.FindElement(By.Id("content-section"));
    if(e.Displayed)
        return e;
});


2添加扩展方法WaitUntilVisible来判断
public static IWebElement WaitUntilVisible(
    this IWebDriver driver,
    By itemSpecifier,
    int secondsTimeout = 10)
{
    var wait = new WebDriverWait(driver, new TimeSpan(0, 0, secondsTimeout));
    var element = wait.Until<IWebElement>(driver =>
    {
        try
        {
            var elementToBeDisplayed = driver.FindElement(itemSpecifier);
            if(elementToBeDisplayed.Displayed)
            {
                return elementToBeDisplayed;
            }
            return null;
        }
        catch (StaleElementReferenceException)
        {
            return null;
        }
        catch (NoSuchElementException)
        {
            return null;
        }
    });
    return element;
}

调用
ChromeDriver driver = new ChromeDriver();
//...省略逻辑代码
element = driver.WaitUntilVisible(By.XPath("//input[@value='Save']"));


3使用ExpectedConditions(已过期)

 public bool waitElementClick()
        {
            System.Threading.Thread.Sleep(3000);
            return true;
        }



WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
            //wait.Until<bool>(e=>waitElementClick()); //等待方法执行完成
 wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("//div/button"))); //等待
wait.Until(ExpectedConditions.UrlToBe(By.XPath("http://")));//等待跳转到摸个页面


4.通过DotNetSeleniumExtras.WaitHelpers判断

Install-Package DotNetSeleniumExtras.WaitHelpers

var wait = new WebDriverWait(driver, new TimeSpan(0, 0, 30));
var element = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.Id("content-section")));


隐式等待
 driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(8);
 driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(8);


强制等待

sleep()

posted @ 2023-03-10 23:26  桃花雪  阅读(207)  评论(0编辑  收藏  举报