【问题标题】:Getting Timeout using Selenium Webdriver使用 Selenium Webdriver 获取超时
【发布时间】:2013-09-14 07:44:24
【问题描述】:

我正在使用 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));
    }

并尝试过:

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

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

有什么帮助吗?

【问题讨论】:

  • 可能是超时或者找不到元素?
  • ID 已更改?试试其他选择器?我们可以看到控件周围的 HTML 吗?发生在所有驱动程序中还是仅限于某个驱动程序?

标签: selenium webdriver selenium-webdriver


【解决方案1】:

尝试使用 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;
};

您可以阅读有关流利等待here

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

希望对你有帮助)

【讨论】:

    【解决方案2】:

    您正在使用 xpath,但在 findElement 中您正在使用 By.Id 将其更改为

    By.xpath("//*[@id='ctl00_ContentPlaceHolder1_AddeCardControl1_txtName']")
    
                            OR
    
    By.id("ctl00_ContentPlaceHolder1_AddeCardControl1_txtName")
    

    如果仍然显示超时错误,请尝试在 xpath 中也指定元素名称,例如

    //div[@id='element_id']
    

    因为这样指定

    //*[@id='ctl00_ContentPlaceHolder1_AddeCardControl1_txtName']
    

    搜索所有元素的 id 属性可能会花费一些时间,因此如果您指定特定元素,则搜索时间将最小化。

    如果它不起作用,请检查您的 xpath 是否正确。

    【讨论】:

    • 是的,这是错字,但我传递了正确的 id.. 让我问你...最快的 Xpath or ID 是什么?哪个更可取?
    • 根据我的经验,xpath 比使用 Id 慢,请参阅这个以获取更多详细信息stackoverflow.com/questions/5313847/…
    猜你喜欢
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    • 2017-12-25
    • 1970-01-01
    相关资源
    最近更新 更多