Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Taking nilesh's answer a step further, you can also allow finer-tuned searches (eg, within the context of a WebElement) by using the SearchContext interface:</p> <pre class="lang-java prettyprint-override"><code>Function&lt;SearchContext, WebElement&gt; elementLocated(final By by) { return new Function&lt;SearchContext, WebElement&gt;() { public WebElement apply(SearchContext context) { return context.findElement(by); } }; } </code></pre> <p>Execution is performed by a FluentWait&lt;SearchContext&gt; instance (instead of WebDriverWait). Give yourself a nice programming interface by wrapping its execution and necessary exception handling in a utility method (the root of your <a href="http://code.google.com/p/selenium/wiki/PageObjects" rel="nofollow">PageObject</a> type hierarchy is a good spot):</p> <pre class="lang-java prettyprint-override"><code>/** * @return The element if found before timeout, otherwise null */ protected WebElement findElement(SearchContext context, By by, long timeoutSeconds, long sleepMilliseconds) { @SuppressWarnings("unchecked") FluentWait&lt;SearchContext&gt; wait = new FluentWait&lt;SearchContext&gt;(context) .withTimeout(timeoutSeconds, TimeUnit.SECONDS) .pollingEvery(sleepMilliseconds, TimeUnit.MILLISECONDS) .ignoring(NotFoundException.class); WebElement element = null; try { element = wait.until(elementLocated(by)); } catch (TimeoutException te) { element = null; } return element; } /** * overloaded with defaults for convenience */ protected WebElement findElement(SearchContext context, By by) { return findElement(context, by, DEFAULT_TIMEOUT, DEFAULT_POLL_SLEEP); } static long DEFAULT_TIMEOUT = 3; // seconds static long DEFAULT_POLL_SLEEP = 500; // milliseconds </code></pre> <p>Example usage:</p> <pre class="lang-java prettyprint-override"><code>WebElement div = this.findElement(driver, By.id("resultsContainer")); if (div != null) { asyncSubmit.click(); WebElement results = this.findElement(div, By.id("results"), 30, 500); if (results == null) { // handle timeout } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload