使用Selenium Webdriver获取超时

Nic*_*ahn 2 selenium webdriver selenium-webdriver

我正在使用Selenium WebDriver,它工作得很好,今天我得到超时,如果我使用下面的代码或得到错误 Unable to find element with id == //*[@id='ctl00_ContentPlaceHolder1_AddControl1_txtName']

我试着用这个:

    public IWebElement GetElementId(string id)
    {
        //return Driver.FindElement(By.Id(id));
        Driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(TimeOut));
        return Driver.FindElement(By.Id(id));
    }
Run Code Online (Sandbox Code Playgroud)

并试过这个:

public IWebElement GetElementId(string id)
{
    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
    IWebElement category = wait.Until<IWebElement>((d) =>
    {
        return d.FindElement(By.Id(el_id));
    });
}
Run Code Online (Sandbox Code Playgroud)

我仍然无法想象如何避免超时或元素未找到错误

任何帮助?

eug*_*kov 5

尝试使用FluentWait类:

public WebElement fluentWait( final By locator ) {
    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
        .withTimeout(30, TimeUnit.SECONDS)
        .pollingEvery(5, TimeUnit.SECONDS)
   .ignoring(NoSuchElementException.class, StaleElementReferenceException.class);

    // use a "custom" ExpectedCondition
    WebElement foo = wait.until( new Function<WebDriver, WebElement>() {
        public WebElement apply( WebDriver driver ) {
            return driver.findElement( locator );
        }
    });
    // usually use one of the built-in ExpectedCondtions
    // WebElement foo = wait.until(
    //     ExpectedConditions.visibilityOfElementLocated( locator );
    return  foo;
};
Run Code Online (Sandbox Code Playgroud)

你可以在这里读到流利的等待

或者,如果没有正确找到定位器,请彻底检查.

希望这可以帮到你)