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

我正在尝试这样做:

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

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


当前回答

你也可以使用隐式等待:

driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);

隐式等待是告诉WebDriver轮询DOM 在试图找到一个或多个元素时的时间 暂时不可用。默认设置为0。设置好后, 为WebDriver对象实例的生命周期设置隐式等待。

其他回答

使用c#扩展方法:我们可以解决等待直到元素可见的问题。 一个特定元素的最大reties是100。

public static bool WaitForElementToBeVisible(IWebDriver browser, By by)
        {
            int attemptToFindElement = 0;
            bool elementFound = false;
            IWebElement elementIdentifier = null;
            do
            {
                attemptToFindElement++;
                try
                {
                    elementIdentifier = browser.FindWebElement(by);
                    elementFound = (elementIdentifier.Displayed && elementIdentifier.Enabled) ? true : false;
                }
                catch (Exception)
                {
                    elementFound = false;
                }

            }
            while (elementFound == false && attemptToFindElement < 100);

            return elementFound;
        }

WebDriverWait将不生效。

var driver = new FirefoxDriver(
    new FirefoxOptions().PageLoadStrategy = PageLoadStrategy.Eager
);
driver.Navigate().GoToUrl("xxx");
new WebDriverWait(driver, TimeSpan.FromSeconds(60))
    .Until(d => d.FindElement(By.Id("xxx"))); // A tag that close to the end

一旦页面是“交互式的”,这将立即抛出异常。我不知道为什么,但是超时就好像它不存在一样。

也许SeleniumExtras。WaitHelpers很管用,但我没试过。这是官方的,但它被拆分为另一个NuGet包。你可以参考c# Selenium 'ExpectedConditions is obsolete'。

我使用FindElements并检查Count == 0。如果为真,则使用await Task.Delay。这真的不是很有效。

你可以使用以下方法:

使用命名空间:

using SeleniumExtras.WaitHelpers;

在代码:

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

你可以在c#中找到类似的东西。

这是我在JUnit - Selenium中使用的

WebDriverWait wait = new WebDriverWait(driver, 100);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));

导入相关的包。

我看到许多解决方案已经张贴,工作很棒!但是,为了防止有人需要其他东西,我想我将发布两个我个人在Selenium c#中使用的解决方案来测试是否存在元素!

public static class IsPresent
{
    public static bool isPresent(this IWebDriver driver, By bylocator)
    {

        bool variable = false;
        try
        {
            IWebElement element = driver.FindElement(bylocator);
            variable = element != null;
        }
        catch (NoSuchElementException){

        }
        return variable;
    }
}

这是第二个:

public static class IsPresent2
{
    public static bool isPresent2(this IWebDriver driver, By bylocator)
    {
        bool variable = true;
        try
        {
            IWebElement element = driver.FindElement(bylocator);
        }
        catch (NoSuchElementException)
        {
            variable = false;
        }
        return variable;
    }
}