How can I overcome Element id exception in Selenium?

我的未来我决定 提交于 2019-12-06 08:09:36

问题


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?


回答1:


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
    }



回答2:


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)



来源:https://stackoverflow.com/questions/11862866/how-can-i-overcome-element-id-exception-in-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!