Reputation: 7708
I have one end user page which have number of controls (textboxes, checkbox, dropdown) let's say 30 . All these enabled from admin panel .
I have enclosed all these in try catch block individually e.g.
try
{
driver.findElement(By.locator); // For Control 1
}
catch(Exception e)
{
}
try
{
driver.findElement(By.locator); // For Control 2
}
catch(Exception e)
{
}
and So On...
The problem is, suppose admin enabled only 1 field which is last in my code. So while executing the script My script is too slow because it check each element one by one and if not found then handle that in catch block until the last element found.
Is there any way to mitigate this time wastage ?
Upvotes: 1
Views: 154
Reputation: 2091
In such scenarios, using FluentWait is the most reliable approach. You should chuck using driver.findElement(By)
and instead create a method getElement(By)
in a commonly accessible class such as BasePage.class
public class BasePage { WebDriver driver; public BasePage(WebDriver driver) { this.driver = driver; } public WebElement getElement(By locator) { // Waiting 30 seconds for an element to be present on the page, checking // for its presence once every 5 seconds. Wait wait = new FluentWait(driver) .withTimeout(30, SECONDS) .pollingEvery(5, SECONDS) .ignoring(NoSuchElementException.class); // Get the web element WebElement element = wait.until(new Function() { public WebElement apply(WebDriver driver) { return driver.findElement(By.id("foo")); } }); return element; } }
Upvotes: 0
Reputation: 145
You can manage your timeouts by doing:
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
You can do this if you want at the beginning of your method and then set it again to what you had and fits best the needs of your site.
More on that: http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp
Upvotes: 0
Reputation: 50809
You can use findElements
and check if there are any elements found. If there aren't any you will get an empty list without an exception. You can build a method that returns the element if it exists or null
if it doesn't
private WebElement findElement(WebDriver driver, By locator) {
List<WebElement> elements = driver.findElements(By.locator);
return elements.size() > 0 ? elements.get(0) : null;
}
findElements(driver, By.locator); // For Control 1
findElements(driver, By.locator); // For Control 2
// ...
Upvotes: 1