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

我正在尝试这样做:

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

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


当前回答

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

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();

其他回答

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

这是我在JUnit - Selenium中使用的

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

导入相关的包。

在Selenium IDE中选择Webdriver格式时,clickAndWait命令不会转换。这里有一个变通办法。添加下面的等候线。实际上,问题是在我的c#代码中的一行1之前发生的单击或事件。但实际上,只要确保在引用By对象的任何操作之前都有一个WaitForElement。

HTML代码:

<a href="http://www.google.com">xxxxx</a>

c# / NUnit代码:

driver.FindElement(By.LinkText("z")).Click;
driver.WaitForElement(By.LinkText("xxxxx"));
driver.FindElement(By.LinkText("xxxxx")).Click();
public bool doesWebElementExist(string linkexist)
{
     try
     {
        driver.FindElement(By.XPath(linkexist));
        return true;
     }
     catch (NoSuchElementException e)
     {
        return false;
     }
}

你可以使用下面的方法

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

我看到许多解决方案已经张贴,工作很棒!但是,为了防止有人需要其他东西,我想我将发布两个我个人在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;
    }
}