How can I overcome Element id exception in Selenium?

1.5k views Asked by At

T set 'id' for GWT widgets in UiBinder itself.

For eg.

Also added in *.gwt.xml

Then I try this in Selenium test case

WebElement element = driver.findElement(By.id("gwt-debug-loginButton"));

Sometimes it works correctly. But some times it throws the following exception,

Unable to locate element: {"method":"id","selector":"gwt-debug-loginButton"} Command duration or timeout: 62 milliseconds

What i need to update? Can anyone help me?

2

There are 2 answers

0
Herokiller On BEST ANSWER

Use WebDriverWait, to search for element after a certain period of time. Something like this.

try {
        (new WebDriverWait(driver, seconds, delay)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
                try {
                    WebElement el = d.findElement(By.id("gwt-debug-loginButton"));
                    return true;
                } catch (Exception e) {
                    return false;
                }
            }
        });
    } catch (TimeoutException t) {
        //Element not found during the period of time
    }
1
Hari Reddy On

When you are trying to find any element on your webpage using the selenium WebDriver. You can make the driver wait until the page loads completely either by using an Implicit Wait or an Explicit Wait

Example of Implicit Wait (This code is typically used after you initialize your driver) -

WebDriver driver = new FirefoxDriver();   
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

The above statement makes the driver wait for 10 seconds if the driver cannot find the element you are looking for. If the driver cannot find it even after 10 seconds the driver throws an exception.

Example of Explicit Wait - This is used specifically for a single WebElement, in your situation -

new WebDriverWait(driver, 20).until(ExpectedConditions.presenceOfElementLocated(By.id("gwt-debug-loginButton")));

The above code will make the driver wait for 20 seconds till it finds the element. If it can't find the element even after 20 seconds it throws a TimeoutException. You can check the API for the ExpectedCondition here(There are many interesting variations you can use with this class)

(Note that the driver will wait for the specified period of time only if it cannot find the element your code is looking for, if the driver finds an element then it simply continues with execution)