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

我正在尝试这样做:

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

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


当前回答

Python:

from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By

driver.find_element_by_id('someId').click()

WebDriverWait(driver, timeout).until(EC.presence_of_element_located((By.ID, 'someAnotherId'))

从EC(导入expected_conditions)中,您还可以选择其他条件。 试试这个:预期条件支持

其他回答

显式等

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

例子:

wait.until(ExpectedConditions.visibilityOfElementLocated(UiprofileCre.UiaddChangeUserLink));
// Wait up to 5 seconds with no minimum for a UI element to be found
WebDriverWait wait = new WebDriverWait(_pagedriver, TimeSpan.FromSeconds(5));
IWebElement title = wait.Until<IWebElement>((d) =>
{
    return d.FindElement(By.ClassName("MainContentHeader"));
});

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

因为我使用一个已经找到的IWebElement来分离页面元素定义和页面测试场景,所以可以这样做:

public static void WaitForElementToBecomeVisibleWithinTimeout(IWebDriver driver, IWebElement element, int timeout)
{
    new WebDriverWait(driver, TimeSpan.FromSeconds(timeout)).Until(ElementIsVisible(element));
}

private static Func<IWebDriver, bool> ElementIsVisible(IWebElement element)
{
    return driver => {
        try
        {
            return element.Displayed;
        }
        catch(Exception)
        {
            // If element is null, stale or if it cannot be located
            return false;
        }
    };
}

我混淆了匿名函数和谓词。这里有一个小帮手方法:

   WebDriverWait wait;
    private void waitForById(string id)
    {
        if (wait == null)
            wait = new WebDriverWait(driver, new TimeSpan(0, 0, 5));

        //wait.Until(driver);
        wait.Until(d => d.FindElement(By.Id(id)));
    }