Selenium WebDriver reliable tests - selenium

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

Related

Selenium - unable to find element- during second time

I am trying to find element like this -
Select servTypeDA = new Select (driver.findElement(By.xpath("//select[#id='ServicesType']")));
servTypeDA.selectByVisibleText(servTypeData);
This works fine perfectly for the first time, when I load this page.
I am trying to do a workflow so when this page loads after couple of steps, for the same line it throws the error -
org.openqa.selenium.NoSuchElementException: Unable to locate element
But I am able to see the element in the screen and its visible but still not accessible by code.
I tried to add wait time, still throws error.
Why the same element is not accessible for the second time?
NoSuchElement is thrown when webdriver is not able to find the element in DOM. The main cause of this is probaly you are searching for the element too early. I would suggest to use some explicit wait and do a check for the element with regular interval.
By byXpath = By.xpath("//select[#id='ServicesType']");
WebElement element = new WebDriverWait(driver,10).until(ExpectedConditions.visibilityOfElementLocated(byXpath));
Select servTypeDA = new Select(element);
servTypeDA.selectByVisibleText(servTypeData);
Or you can set implicitlyWait which is by default 0.
By setting this, Webdriver will wait for given amount of time before throwing NoSuchElementException
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
It will save your effort of adding webdriverWait almost before each Element.
The way that webdriver works is that each page load it copies the page. So what is shown does not have to be what is loaded in the webdriver instance. For example if you change the webpage via JavaScript, the webdriver would not be aware of it.
These often is the couse for
NoSuchElementException
or
StaleElementReferenceException
I found that the only cure for this is to catch the exception and try again. I had to create a new function for each type of action. I will show you my example for "selectByVisibleText"
public void selectByLabel(final By by, final String label){
act(by, 3, new Callable<Boolean>() {
public Boolean call() {
logger.trace("Trying to select label: "+label+" in select box "+stripBy(by) );
Boolean found = Boolean.FALSE;
int attempts = 0;
wait.until(ExpectedConditions.refreshed(ExpectedConditions.elementToBeClickable(by)));
Select select = new Select(driver.findElement(by));
select.selectByVisibleText(label);
if(isLabelSelected(by,label)){
found = Boolean.TRUE; // FOUND IT
logger.info("Selected value "+label+" in select box "+stripBy(by));
}
return found;
}
});
}
It will retry for a few times.
All my special implementetation of action use a function for catching exceptions
private void act(By by, int tryLimit, boolean mode, Callable<Boolean> method){
logger.trace( "Looking for element: " + stripBy(by) );
driver.manage().timeouts().implicitlyWait( 5, TimeUnit.SECONDS );
boolean unfound = true;
int tries = 0;
while ( unfound && tries < tryLimit ) {
tries += 1;
try {
WebDriverWait wait = new WebDriverWait(driver, 500);
unfound = !method.call(); // FOUND IT, this is negated since it feel more intuitive if the call method returns true for success
} catch ( StaleElementReferenceException ser ) {
logger.error( "ERROR: Stale element exception. " + stripBy(by) );
unfound = true;
} catch ( NoSuchElementException nse ) {
logger.error( "ERROR: No such element exception. " + stripBy(by)+"\nError: "+nse );
unfound = true;
} catch ( Exception e ) {
logger.error( e.getMessage() );
}
}
driver.manage().timeouts().implicitlyWait( Constants.DEFAULT_IMPLICIT_WAIT, TimeUnit.SECONDS );
if(unfound)
Assert.assertTrue(false,"Failed to locate element by locator " + stripBy(by));
}

Waiting for same XPATH used on different pages with 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;
}
}
}

Test causing error occasionally

I have really weird issue when running a Selenium Webdriver test.
My code
driver.findElement(By.id("id")).click();
driver.manage().timeouts().implicitlyWait(180, TimeUnit.SECONDS);
driver.findElement(By.xpath("//a[starts-with(#href,'/problematic_url')]")).click();
driver.manage().timeouts().implicitlyWait(180, TimeUnit.SECONDS);
driver.findElement(By.className("green_true")).click();
The elements actually exist. I can even see that the problematic url is clicked by the webdriver, but then nothing happens. Browser won't go the page and won't find green_true element. Error is caused. But only occasionally. Sometimes test runs as it should.
Can anyone tell how can this be?
I cannot use exact urls, because they vary according to selected language.
try to use an explicit wait when clicking on a dynamic element. Wait until the elements appear on the web browser or the actions are applied on them. You can use this pattern :
final FluentWait<WebDriver> wait =
new FluentWait<WebDriver>(getDriver())
.withTimeout(MASK_PRESENCE_TIMEOUT, TimeUnit.SECONDS)
.pollingEvery(100, TimeUnit.MILLISECONDS)
.ignoring(NoSuchElementException.class)
.ignoring(StaleElementReferenceException.class)
.withMessage("Time out while waiting the element is loaded");
wait.until(new Predicate<WebDriver>() {
#Override
public boolean apply(final WebDriver driver) {
return ! driver.findElements(By.id("id")).isEmpty();
}
});
well. would suggest to modify in the following way:
instead of
driver.findElement(By.id("id")).click();
driver.manage().timeouts().implicitlyWait(180, TimeUnit.SECONDS);
driver.findElement(By.xpath("//a[starts-with(#href,'/problematic_url')]")).click();
driver.manage().timeouts().implicitlyWait(180, TimeUnit.SECONDS);
driver.findElement(By.className("green_true")).click();
try use following:
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; } ;
fluentWait(By.id("id")).click();
fluentWait(By.xpath("//a[starts-with(#href,'/problematic_url')]")).click();
fluentWait(By.className("green_true")).click();
The problem can be that you prolly get some AJAX on the page after interacting with elements(clicking, etc). IMHO we need to use a lil bit more robust wait mechanism.
a piece of advice: when you got xpath for webelement or css selector do not forget to verify found locators in fireBug, ffox extension.
Regards.

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();