Waiting for same XPATH used on different pages with Selenium - selenium

I'm using Selenium Webdriver and have run into the following issue with my app under test.
The app has multiple pages each with an appropriate ".page-title" element which contains the name of the page (e.g. "Other Documents"). As the tests navigate around the app they assert that the browser is on the expected page using these elements before doing other stuff.
The issue is that if you click a button in the app which performs an action, then check that you're on the right page (e.g. check page-title element displays correct text), Webdriver doesn't wait for the action to be performed (e.g. new page load), it returns straight away and the test fails.
If you add a short thread sleep (500ms) between performing the action and checking you're on the right page, then you get StaleElementReferenceException (some of the time) and if you add a large thread sleep the test passes (but not quite all the time).
My aim is to reduce the flakiness of the tests, does anyone have a suggestion as to how I can do this without Thread.sleep?

instead of inserting thread.sleep method explicity
do try the WebDriver in built Implicitwait method..(C# code snippet)
Driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(Max_Time_Limit));
This makes WebDriver to wait till the element is visible/available. In case if it finds elements before the Max_Time_Limit, it snaps out of sleep mode and resumes the execution.
So no hassle of waiting till the Hard bound Max_Time_Limit.This way it helps speeding up your execution Time as well.
I hope this helps...All the best :-)

Try using this wait: using this you can wait for max time 15 secs/wait for the expected condition to be true i.e. wait for some element to be present.
You can give the xpath of some element on the next page, when that element is visible then the next step will be executed.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("\xpath of some element on the next page")));
//Assert page title
driver.getTitle();

use fluentWait mechanism . Considered to be a robust approach. As documentation on fluent wait gives:
An implementation of the Wait interface that may have its timeout and polling interval configured on the fly.
Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. Furthermore, the user may configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page.
details you can get here
here is the code of method I use:
public WebElement fluentWait(final By locator){
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(
new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
}
);
return foo; } ;
String xPathElement="...blablabla...";
fluentWait(By.xpath(xPathElement)).click();
//fluentWait(By.xpath(xPathElement)).getText();
Hope it works for you.

You can use Selenium's ExpectedCondition.
The code below (written in JAVA) waits for a maximum of inTimeout seconds for the element you want to appear. If the element appears sooner, it ends the wait.
public static void wait(WebDriver b,long inTimeout) {
final SlnDriver browser=b;
final long NO_LOADING_TIMEOUT = inTimeout;
class HasCondition implements ExpectedCondition<Boolean> {
#Override
public Boolean apply(WebDriver d) {
Boolean expected=false;
WebElement e = browser.findElement(By.xpath("blabla"));
if (e.getText().contains("TextYouWant")) {
expected= true;
break;
}
}
return expected;
}
}
}
for (;;) {
try {
new WebDriverWait(browser, NO_LOADING_TIMEOUT).until(new HasCondition());
} catch (TimeoutException e) {
return;
}
}
}

Related

Selenium click and wait

I have a registration form that register many users ,the problem in the first loop when I click on create it go too fast and didn't register the first one and resister the second ...,
so I use Thread.sleep(500);
I want to avoid using sleep
is there a way to do it
here is my code
#Given("user on registration page and create users")
public void user_on_registration_page_and_create_users() throws InterruptedException {
System.out.println(userLoginPageDataList);
for(UserLoginPageData userLoginPageData:userLoginPageDataList){
userRegistrationPage.init();
logger.info("*************************************** init the driver && go to registration page http://localhost:4200/register");
logger.info("*************************************** reading line "+userLoginPageData.getRowIndex() +" from Excel file");
userRegistrationPage.enterUserLogin(userLoginPageData.getUsername());
userRegistrationPage.enterUserPassword(userLoginPageData.getPassword());
userRegistrationPage.enterUserRole(userLoginPageData.getUserRole());
userRegistrationPage.clickOnCreate();
// Thread.sleep(500);
logger.info(userLoginPageData.getUsername()+" is registred");
}
}
You can use explicit(smart) wait.
WebDriverWait w = new WebDriverWait(driver, 5); //will wait 5 seconds most , but if element is visuble in the third second it will wait 3 sec.
w.until(ExpectedConditions.visibilityOfElementLocated(By.id("submit_btn")));
read more on When to use explicit wait vs implicit wait in Selenium Webdriver?
One of the possible solutions (when you work with PageFactory) is to implement your own Locator that can be extended from AjaxElementLocator.
Say you have a form and the form has some noticeable property saying that it is ready to accept the input (this might be some button state or displaying some label, etc).
So you can initialize your page object in the way its fields will be "available" if that condition is met.
This can be achieved using your custom Locator/LocatorFactory in your PageFactory.init().
For example here is the form of two fields. The condition saying it is ready for interaction is then create button is enabled:
class MyForm {
#FindBy(id = "user")
WebElement user;
#FindBy(id = "create")
WebElement create;
public MyForm(SearchContext searchContext){
PageFactory.initElements(field -> new AjaxElementLocator(searchContext, field, 10){
#Override
protected boolean isElementUsable(WebElement element) {
return create.isEnabled();
}
}, this);
}
}
Unless create button is enabled any attempt to invoke fields methods would be failing and the script will fail in 10 seconds of retries.
More details about how you use the conditions with page objects you can find in this post.

Selenium extremely slow on reading the DOM

Selenium interaction with DOM seems extremely slow while doing couple of things in every page instantiation. Throughout the site we have visible spinner that indicates any outstanding API calls resolved or not. In summary I have three methods that make sure the stability of page before performing any action.
Check for the DOM ready state
Check for any outstanding JQuery calls
Check for loading spinners
All of these three are done as a part of the page object instantiation with following methods.
public static void waitForLoadingAllSpinnersAnywhere(final WebDriver driver){
final WebDriverWait wait = new WebDriverWait(driver, timeout);
wait.until(waitForDomReadyState());
wait.until(waitForjQueryToBeInactive());
List<WebElement> elements = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(spinnersLoacator));
for(WebElement element: elements){
wait.until(invisibilityOfElementLocated(element));
}
}
private static ExpectedCondition<Boolean> waitForDomReadyState(){
return new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver d){
return ( ((JavascriptExecutor) d).executeScript("return document.readyState;").equals("complete"));
}
};
}
private static ExpectedCondition<Boolean> waitForjQueryToBeInactive(){
return new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver d){
return (Boolean) ( ((JavascriptExecutor) d).executeScript("return jQuery.active == 0;"));
}
};
}
public static ExpectedCondition<Boolean> invisibilityOfElementLocated(final WebElement element){
return new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driver){
try{
return !element.isDisplayed();
} catch (NoSuchElementException | StaleElementReferenceException e){
// Returns true because the element is not present in DOM.
// The
// try block checks if the element is present but is
// invisible or stale
return true;
}
}
};
}
Taking an example of a page(say patient page) which has good number of API calls and fetches a lot of data. For a initial class instantiation it takes about 17s(log below). My Selenium knowledge says, the subsequent page instantiation should not take same or more time to check DOM ready state, or JQuery call or spinner waits since there is nothing changing at all. However, every time new page instantiate I see it takes same amount of time taken to check all these three. What's happening there? Does Selenium actually tries to interact with Server every time I do these or just interaction with the client is slow for some reason? If so, what could be the possible answer?
Console log
==== [[Finished waiting for 8 spinner elements found on widget [Patient] after [17] s]]
==== [[Start waiting for 8 spinner elements found on widget [Patient] ]]
==== [[Finished waiting for 8 spinner elements found on widget [Patient] after [17] s]]
==== Browser on [[[Patient]]]
==== [[Start waiting for 8 spinner elements found on widget [Patient] ]]
==== [[Finished waiting for 8 spinner elements found on widget [Patient] after [17] s]]
Environment:
Selenium 2.48
Firefox 38
I also tried with Selenium 2.52 and firefox 44 with same result
Selenium handles all the waiting on the client side with a request sent to the server for every evaluation until the condition is met.
It can quickly degenerate in case of high latency, especially if there are a lot of calls. Moreover some evaluations require a script injection which doesn't help either.
So the best way to improve the performance in your case would be to use a single asynchronous JavaScript call:
public static void waitForLoadingAllSpinnersAnywhere(final WebDriver driver) {
const String JS_WAIT_SPINNERS =
"var callback = arguments[0]; " +
"(function fn(){ " +
" if (document.readyState == 'complete' && jQuery.active == 0) { " +
" var elts = $('.spinners'); " +
" if (elts.length == 8 && !elts.is(':visible')) " +
" return callback(); " +
" } " +
" setTimeout(fn, 60); " +
"})();";
((JavascriptExecutor)driver).executeAsyncScript(JS_WAIT_SPINNERS);
}
To initialize the timeout:
driver.manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS);
Your test seems to be all non-native calls and so Firefox should work for you but I am surprised that the Firefox native call to driver.navigate() even worked for you to get to the inital page if you were using 44 and 48. It is well known that 31.6.0 was the last supported native Firefox version. So, I would say you should use Chrome until you figure this out.
But, to answer your thing about slowness. The way you wrote your code, you are highly dependent on jQuery and I would imagine your are having an issue with your calls to jQuery code being delayed, which propagates out to your Selenium test, and further impacted by the fact that your looping through multiple spinners. One thing I have noticed before is that if a page is busy running ajax calls, then your Selenium calls with JavascriptExecutor might have to wait in line for those to give up bits of processor time.
What would I do differently?
Well, I would write my spinner waits to operate on the DOM instead of calling JavascriptExecutors to jQuery. Maybe in your case, this is not an option, but I think a well thought out plan can improve the efficiency of your page ready workflow.

Selenium WebDriver reliable tests

I know that this question was asked many times before, but I still couldn't find a solution that works for me. When I run my tests with Selenium WebDriver most of the times they fail with "NoSuchElementException". I tried using Explicit and Implicit Waits but nothing seems to work. So, is there any other way besides using Waits in which I can make my tests more reliable?
I'm using selenium-java-2.31.0 with FirefoxDriver. Below are some samples of code I tried to make my tests more reliable:
public void waitAndClickElement(WebDriver driver, final By selector) {
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(50, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement elementToClick = wait
.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(selector);
}
});
waitForElementVisible(driver, selector);
elementToClick.click();
}
..and this:
public WebElement waitForElementPresent(WebDriver driver, final By selector){
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(70, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement elementToClick = wait
.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(selector);
}
});
return elementToClick;
}
...and this:
WebDriverWait wait = new WebDriverWait(driver, 50);
WebElement user_name = wait.until(visibilityOfElementLocated(By.xpath("//*#id='userName']")));
...and this:
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
...and finally one of the tests that I try to make more reliable:
#Test
public void test1{
waitAndClickElement(driver, By.xpath("//*[#id='linkLogIn']"));
waitForElementPresent(driver, By.xpath("//*[#id='userName']")).sendKeys("name");
waitForElementPresent(driver, By.xpath("//*[#id='inputEmail']")).sendKeys("email#gmail.com");
waitForElementPresent(driver,By.xpath("//*[#id='resetPassword']")).click();
assertTrue(isElementPresent(By.xpath("//*[#id='moduleMain']")));
}
Thank you!
Try below custom method. It works fine for me,
public boolean waitForElementToBePresent(By by, int waitInMilliSeconds) throws Exception
{
WebDriver driver = getDriver();
int wait = waitInMilliSeconds;
int iterations = (wait/250);
long startmilliSec = System.currentTimeMillis();
for (int i = 0; i < iterations; i++)
{
if((System.currentTimeMillis()-startmilliSec)>wait)
return false;
List<WebElement> elements = driver.findElements(by);
if (elements != null && elements.size() > 0)
return true;
Thread.sleep(250);
}
return false;
}
Use it like,
waitForElementToBePresent(By.id("linkLogIn", 5000);
driver.findElement(By.id("linkLogIn")).click();
WebDriver is perfectly stable if you handle exceptions properly. The problem is that the methods of ExpectedConditions class don't handle the exceptions for you although most people will reply to your question as if it does.
You can try my method if you want. This method returns in between 0 to 90 seconds, depending on the scenario. You may prefer to alter this method a little, but it should work. The important concepts here are:
1. Use the new FluentWait class with the .ignoring method (or .ignoreAll() ).
2. Use findElement() BUT make sure you catch (and nicely handle) the possible
exceptions (that you are ignoring in the wait).
3. Use a loop to retry after exceptions but govern that by either time or
# of tries.
And the code:
public WebElement getElementByLocator( final By locator ) {
LOGGER.info( "Get element by locator: " + locator.toString() );
final long startTime = System.currentTimeMillis();
Wait<WebDriver> wait = new FluentWait<WebDriver>( driver )
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring( NoSuchElementException.class )
.ignoring( StaleElementReferenceException.class ) ;
int tries = 0;
boolean found = false;
WebElement we = null;
while ( (System.currentTimeMillis() - startTime) < 91000 ) {
LOGGER.info( "Searching for element. Try number " + (tries++) );
try {
we = wait.until( ExpectedConditions.visibilityOfElementLocated( locator ) );
found = true;
break;
} catch ( StaleElementReferenceException e ) {
LOGGER.info( "Stale element: \n" + e.getMessage() + "\n");
} catch ( NoSuchElementException nse ) {
LOGGER.info( "No such element: \n" + nse.getMessage() + "\n");
}
}
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
if ( found ) {
LOGGER.info("Found element after waiting for " + totalTime + " mill." );
} else {
LOGGER.info( "Failed to find element after " + totalTime + " mill." );
}
return we;
}
When you run findElement, you will get an error when it's not found. This occurs for one of three reasons:
Your selector is wrong
If the selector is wrong, the best thing to do debug until you get to that spot and pause test execution. Then use the console to figure out the correct selector to find the element.
The element isn't there
You may notice in your first action that the element you're looking for isn't actually there. In that case, find out why you're in that wrong state and fix it. If you're expecting the element to not be there, Here is a great C# example on how to extend your IWebElement object to allow for a .Exists() method.
The element is late
Determining if the element is just late is easy. Run the test normally once and then run in debug mode stepping over each step manually. If your normal test run fails while your manual steps work, you know you found your issue. Typically the issue is due to AJAX loads not occurring on page load. In these instances, a good webdev will typically add some kind of spinner image that you can easily search for. I created a helper method called WaitForPageLoad() that first waits till page load, then verifies that the spinner isn't present, then waits again for page load to complete. You want 2 page load waits because a modal will spin then load while a new page load will load then spin. Finally, the page is complete, your element will be present.
I have faced with the same type of problem, while using WebDriver with C#.
I can propose 2 different ways on how you can avoid(not completely, but minimize) NoSuchElementException in your tests:
First of all you should figure out how your application works - does it use a lot of Ajax and other asynch. requests/responses. Then you can use explicit wait for every element, which can not be located at once.
You can write your own implementation of WebElement class based on Selenium WebDriver WebElement class.
Main idea - everytime you will use your webelement it will relocated - so you will not be worry about NoSuchElement or StaleElementException.
Did you try to catch element by element without all theses wait and wait.until?
simply like : WebElement username = driver.findelement(By.id("userName"));
Can you drop your html by the way ?
EDIT:
What i can suggest is :
protected void sleep(int i) {
driver.manage().timeouts().implicitlyWait(i, TimeUnit.SECONDS);
}
#test
void test(){
driver.findElement(By.id("linkLogIn")).click(); sleep(6);
driver.findElement(By.id("userName")).sendKeys("user"); sleep(1);
driver.findElement(By.id("inputEmail")).sendKeys("mail#gmail.com"); sleep(1);
driver.findElement(By.id("resetPassword")).click(); sleep(10);
Assert.assertTrue(isElementPresent(By.id("moduleMain")));
}
Well your code tells me that you are only waiting until the element is present.
waitForElementPresent(driver, By.xpath("//*[#id='userName']")).sendKeys("name");
waitForElementPresent(driver, By.xpath("//*[#id='inputEmail']")).sendKeys("email#gmail.com");
It tells me nothing that you clicked the field, then using sendkeys to input the text.
How about adding click
waitForElementPresent(driver, By.xpath("//*[#id='userName']"));
driver.findElement(by.id ="userName").click();
driver.findElement(by.id ="userName").sendKeys("name");
The problem is the mouse focus on webdriver, it need to be focused in appropriate field AFAIK

Mink with Selenium2: follow all redirects

How to force Selenium2 to follow all redirects before doing some asserts?
Scenario: Guest member can pay with card
When I go to "/test"
#test page redirects to "/auth" which then redirects to "/main"
Then I should be redirected to "/main"
I figured that I could simply wait:
/**
* #Then /^I should be redirected to "([^"]*)"$/
*/
public function assertRedirect($url)
{
$this->getSession()->wait(10000);
$this->assertPageAddress($url);
}
The problem is that however long I wait, I always end up on "/auth" page, not "/main".
UPDATE: It turns out the problem is mythical, selenium isn't doing anything special and browser is following redirects by default as it usually does. It my case the page that was supposed to produce redirect was actually sending 200 response.
I have run into a situation similar to yours. I set up a wait method that polls for an element every second for x number of seconds waiting for the element to become visiable. I then pass an Xpath to an element only available on the last page, or /main in your case. Here is the method I use in java.
public void waitForElement(WebDriver driver, final String xpath)
{
//Set up fluentWait to wait for 35 seconds polling every 1
Wait<WebDriver> fluentWait = new FluentWait<WebDriver>(driver)
.withTimeout(35, TimeUnit.SECONDS)
.pollingEvery(1, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement element;
//Look for element, if not found start fluentWait
try
{
element = driver.findElement(By.xpath(xpath));
}
catch (WebDriverException e)
{
logger.info("[getElementByXpath] Element not initially found. Starting fluentWait ["+xpath+"]");
try
{
element = fluentWait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver d) {
return d.findElement(By.xpath(xpath));
}
});
}
catch (WebDriverException f)
{
logger.info("[getElementByXpath] FluentWait findElement threw exception:\n\n" + f +"\n\n");
throw new WebDriverException("Unable to find element ["+xpath+"]");
}
}
//Once we've found the element wait for element to become visible
fluentWait.until(ExpectedConditions.visibilityOf(element));
}
You may or may not need the last fluentWait for visibility as when the element is returned you will be on the correct /main page.
Hope this helps. Good Luck!

Selenium WebDriver: Fluent wait works as expected, but implicit wait does not

I am new to Selenium WebDriver and am trying to understand the correct way to 'wait' for elements to be present.
I am testing a page with a bunch of questions that have radio button answers. As you select answers, Javascript may enable/disable some of the questions on the page.
The problem seems to be that Selenium is 'clicking too fast' and not waiting for the Javascript to finish. I have tried solving this problem in two ways - explicit waits solved the problem. Specifically, this works, and solves my issue:
private static WebElement findElement(final WebDriver driver, final By locator, final int timeoutSeconds) {
FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(timeoutSeconds, TimeUnit.SECONDS)
.pollingEvery(500, TimeUnit.MILLISECONDS)
.ignoring(NoSuchElementException.class);
return wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver webDriver) {
return driver.findElement(locator);
}
});
}
However, I would prefer to use an implicit wait instead of this. I have my web driver configured like this:
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
This does not solve the problem and I get a NoSuchElementException. Additionally, I do not notice a 10 second pause - it just errors out immediately. I have verified this line in the code is being hit with a debugger. What am I doing wrong? Why does implicitlyWait not wait for the element to appear, but FluentWait does?
Note: As I mentioned I already have a work around, I really just want to know why Implicit wait isn't solving my issue. Thanks.
Remember that there is a difference between several scenarios:
An element not being present at all in the DOM.
An element being present in the DOM but not visible.
An element being present in the DOM but not enabled. (i.e. clickable)
My guess is that if some of the page is being displayed with javascript, the elements are already present in the browser DOM, but are not visible. The implicit wait only waits for an element to appear in the DOM, so it returns immediately, but when you try to interact with the element you get a NoSuchElementException. You could test this hypothesis by writing a helper method that explicits waits for an element to be be visible or clickable.
Some examples (in Java):
public WebElement getWhenVisible(By locator, int timeout) {
WebElement element = null;
WebDriverWait wait = new WebDriverWait(driver, timeout);
element = wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
return element;
}
public void clickWhenReady(By locator, int timeout) {
WebDriverWait wait = new WebDriverWait(driver, timeout);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(locator));
element.click();
}
basic idea is in the following:
Explicit wait
WebDriverWait.until(condition-that-finds-the-element);
Implicit wait
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
In other words, explicit is associated with some condition to be held, whereas implicit with some time to wait for something.
see this link
To make work fluentWait properly try this:
public WebElement fluentWait(final By locator){
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofMillis(100))
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(
new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
}
);
return foo;
};
Hope this helps)
Word of warning for a common mistake:
Once you set implicit waiting, you cannot use explicit- or fluent wait until you reset the implicit waiting again. This means that ExpectedConditions, which contain driver.findElement calls will not work as expected with implicit wait! You'll often encounter cases where you want to check for an element or its non-existence instantly - but you can't do that either.
After ~2 years of experience and problems with this I strongly recommend against using implicit wait.
A kotlin version of the https://stackoverflow.com/users/503060/hedley answer:
clickWhenReady("#suggest",10,driver)
via
fun clickWhenReady(selector: String,timeout: Long, webdriver: WebDriver?) {
val wait = WebDriverWait(webdriver, timeout);
val element = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(selector)));
element.click();
}
I wrote a small method in C# using the WebDriverWait class. Works great for me.
public static void WaitForAjaxElement(IWebDriver driver, By byElement, double timeoutSeconds)
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutSeconds));
wait.Until(x => x.FindElement(byElement));
}
Using:
WaitForAjaxElement(driver, By.ClassName("ui-menu-item"), 10);
Hope it helps.
From Seleniumhq.com:
An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.
If you post your test code what you actually want to do I can provide more information.
I have another solution to solve this issue (only for IE, i never try other browser):
1) after create Selenium driver instance, you can get its ie COM instance
Add-Type -Path .\SePSX.NET35\WebDriver.dll
$ieDriver = New-Object "OpenQA.Selenium.IE.InternetExplorerDriver"
$ieShell = $null
$shell_apps = (New-Object -ComObject Shell.Application).Windows()
foreach($app in $shell_apps)
{
if ($app.LocationURL -eq $ieDriver.URL)
{
$ieShell = $app
break
}
}
if ($ieShell -eq $null)
{
throw "Can't get WebDriver IE Instance"
}
2) after each call GotoURL or click action, check $ieShell.Busy status, it will wait for until page is loaded.
$ieDriver.Navigate().GotoUrl("www.google.com")
while ($ieShell.Busy -eq $true) {sleep 1}
then call Selenium driver to get element id and do the further action
$ieDriver.FindElementById ...
use this way, you don't need to set page load and findElement timeout for Selenium
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver);
wait.pollingEvery(250, TimeUnit.MILLISECONDS);
wait.withTimeout(20, TimeUnit.SECONDS);
wait.ignoring(NoSuchElementException.class);
Predicate<WebDriver> predicate = new Predicate <WebDriver>()
{
public boolean apply(WebDriver arg0) {
WebElement element = arg0.findElement(By.id("colorVar"));
String color = element.getAttribute("color");
System.out.println("The color if the button is " + color);
if(color.equals("blue"))
{
return true;
}
return false;
}
};
wait.until(predicate);
Below is the code equivalet code for fluient wait in c#.Net using DefaultWait.
IWait<IWebDriver> wait = new DefaultWait<IWebDriver>(driver);
wait.Timeout = TimeSpan.FromSeconds(10);
wait.PollingInterval = TimeSpan.FromMilliseconds(100);
IWebElement elementt = wait.Until<IWebElement>(ExpectedConditions.ElementIsVisible(By.Id("selectedfirstlast1")));
SelectElement se = new SelectElement(driver.FindElement(By.Id("selectedfirstlast1")));
element = se.SelectedOption;
if (element.Text.Contains("Mumbai") && element.Selected)
driver.FindElement(By.XPath("//table/tbody/tr[2]/td[7]/a")).Click();