1
votes

I'm using Selenium 2.0 web driver. My script fails occasionally whenever I try locating something in my page. It throws an exception:

Unable to locate element: {"method":"id","selector":"username"};

part of my code:

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

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

It passes successfully sometimes with the same code. I don't understand what's happening.

2

2 Answers

4
votes

Sometimes this happens because of the page is loading slowlier than you expected. I am doing workaround by applying my own wrapper helper. It looks like this:

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

And later in the code:

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

This approach will try to find it and if not found, sleep for 200 miliseconds and try again. If not found in 3 seconds (editable), it will crash (you will probably have to say in the method that it throws some Exception)

I apply it whenever I am not sure how fast the page will load...

3
votes

The best solution to your problem is by making the driver wait until the id element loads in the browser by using the WebDriverWait Object -

new WebDriverWait(driver, 10).until(new ExpectedCondition<Boolean>() {

        public Boolean apply(WebDriver arg0) {

            WebElement element = driver.findElement(By.id("username"));


            return element.isDisplayed();
        }
    });

This makes sure that the driver stops checking if the id element has loaded. If it does not load within 10 secs an timedOutException will be thrown.