【问题标题】:Locating element by id fails in Selenium 2.0 Webdriver在 Selenium 2.0 Webdriver 中按 id 定位元素失败
【发布时间】:2012-04-05 17:43:53
【问题描述】:

我正在使用 Selenium 2.0 网络驱动程序。每当我尝试在我的页面中查找某些内容时,我的脚本偶尔会失败。它抛出一个异常:

无法定位元素:{"method":"id","selector":"username"};

我的部分代码:

driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

WebElement userName = driver.findElement(By.id("username"));
userName.clear();
userName.sendKeys("admin");

有时使用相同的代码会成功通过。我不明白发生了什么。

【问题讨论】:

    标签: webdriver selenium-webdriver


    【解决方案1】:

    有时会发生这种情况,因为页面加载速度比您预期的要慢。我正在通过应用我自己的包装器助手来解决问题。它看起来像这样:

     private WebElement foundElement;
    
     public WebElement find(By by){
        for (int milis=0; milis<3000; milis=milis+200){
           try{
           foundElement = driver.findElement(by);
    
           }catch(Exception e){
             Thread.sleep(200);
           }
    
         }
        return foundElement;
     }
    

    以及后面的代码:

    WebElement userName = find(By.id("username"));
    

    此方法将尝试找到它,如果未找到,则休眠 200 毫秒并重试。如果在 3 秒内没有找到(可编辑),它会崩溃(你可能不得不在方法中说它会抛出一些异常)

    每当我不确定页面的加载速度时,我都会应用它...

    【讨论】:

    • 谢谢。让我试试你的方法。会让你知道事情是如何运作的。
    • 使用 Hari Reddy 所展示的流畅等待,如果比这种显式等待要好得多。
    【解决方案2】:

    解决问题的最佳方法是使用 WebDriverWait 对象让驱动程序等到 id 元素加载到浏览器中 -

    new WebDriverWait(driver, 10).until(new ExpectedCondition<Boolean>() {
    
            public Boolean apply(WebDriver arg0) {
    
                WebElement element = driver.findElement(By.id("username"));
    
    
                return element.isDisplayed();
            }
        });
    

    这确保驱动程序停止检查 id 元素是否已加载。如果它没有在 10 秒内加载,则会抛出 timedOutException。

    【讨论】:

    • 对于任何可能关心的人:在 C# 中,WebDriverWait 对象是 Selenium.Support NuGet 包的一部分..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-15
    • 2019-08-31
    • 1970-01-01
    • 2018-10-18
    • 1970-01-01
    • 2015-05-04
    相关资源
    最近更新 更多