本文介绍了使用Selenium Webdriver获取超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Selenium WebDriver,并且一切正常,今天,如果我使用下面的代码或者出现错误Unable to find element with id == //*[@id='ctl00_ContentPlaceHolder1_AddControl1_txtName']

I am using Selenium WebDriver and its was working all fine and today i am getting either timeout if i use the below code or getting the error 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));
    }

并尝试了此操作:

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

我仍然不知道如何避免超时或找不到元素错误

I am still couldn't figured how to avoid time-out or element not found error

有什么帮助吗?

推荐答案

尝试使用FluentWait类:

Try using the FluentWait class:

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;
};

您可以阅读有关流畅的等待的信息此处

you can read about fluent wait here

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

Or if not check thoroughly if you found locator properly.

希望这对您有帮助)

这篇关于使用Selenium Webdriver获取超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 17:27