Search code examples
seleniumtimeout

Timeout on element find in Selenium with Java


When you do something like

WebElement tab = driver.findElement(By.xpath("//table")) 

you can issue a command like

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

to change the timeout. But now, what if you want to do something like the following:

 public String getCellText(WebElement tab) {
 {
     WebElement td = tab.findElement(By.xpath(".//td"));
     return td.getText();
 }

You can't do a

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

Is there a way to change the timeout? This is expecially interesting when you have an element that is a table, and you want to find the rows underneath, if it is possible there are no rows. If you did a tab.findElements(By.xpath("tr")) and there are no rows it can take up to a minute to return.

Is there a way to set timeout for an element as above?


Solution

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

    This is a implicit wait.
    The implicit wait is set for the life of the WebDriver object instance.

    Since tab is web element , you can't do :

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

    You may opt for Explicit wait for change the timeout for specific conditions.

    Code would be something like this :

    new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(locator));  
    

    It return a web element. you can have it like this also :

    WebElement element =   new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(locator));