我想确保在webdriver开始做事情之前,一个元素是存在的。

我正在尝试这样做:

WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 0, 5));
wait.Until(By.Id("login"));

我主要是挣扎如何设置匿名功能…


当前回答

 new WebDriverWait(driver, TimeSpan.FromSeconds(10)).
   Until(ExpectedConditions.PresenceOfAllElementsLocatedBy((By.Id("toast-container"))));

其他回答

试试下面的代码:

 New WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(Function(d) d.FindElement(By.Id("controlName")).Displayed)

下面是如何在Selenium中等待一个条件:

    WebDriverWait wait = new WebDriverWait(m_driver, TimeSpan.FromSeconds(10));
    wait.Until(d => ReadCell(row, col) != "");

ReadCell(row, col) != ""可以是任何条件。这样做是因为:

它是我的 允许内联

显式等

public static  WebDriverWait wait = new WebDriverWait(driver, 60);

例子:

wait.until(ExpectedConditions.visibilityOfElementLocated(UiprofileCre.UiaddChangeUserLink));

我正在用这个,效果很好:

public static bool elexists(By by, WebDriver driver)
{
    try
    {
        driver.FindElement(by);
        return true;
    }
    catch (NoSuchElementException)
    {
        return false;
    }
}

public static void waitforelement(WebDriver driver, By by)
{
    for (int i = 0; i < 30; i++)
    {
        System.Threading.Thread.Sleep(1000);
        if (elexists(by, driver))
        {
            break;
        }
    }
}

当然,您可以添加超过30次的尝试,并将周期缩短到1秒以内进行检查。

用法:

waitforelement(driver, By.Id("login"));
IWebElement login = driver.FindElement(By.Id("login"));
login.Click();

我们可以这样实现:

public static IWebElement WaitForObject(IWebDriver DriverObj, By by, int TimeOut = 30)
{
    try
    {
        WebDriverWait Wait1 = new WebDriverWait(DriverObj, TimeSpan.FromSeconds(TimeOut));
        var WaitS = Wait1.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.PresenceOfAllElementsLocatedBy(by));
        return WaitS[0];
    }
    catch (NoSuchElementException)
    {
        Reports.TestStep("Wait for Element(s) with xPath was failed in current context page.");
        throw;
    }
}