How to wait until loading window close or visible false - java

I have developed selenium automation framework using JAVA and I facing a problem.
When I click on any button say Filter or clear filter application display a loading window and after that, we are able to perform next action.
i have added following code to wait until loading window visible false but its not working.
wait.until(ExpectedConditions.invisibilityOf(webElement));
System.out.println("Wait Untill Loading Window Closed");
existFlag=true;
in web element i passing that loading window XPATH. Every time code not wait for window to be closed start clicking on button and throw exception
unknown error: Element ... is not clickable at point (178, 391). Other element would receive the click:
I also added code for click
wait.until(ExpectedConditions.elementToBeClickable(webElement));
webElement.click();
return true;
Please help how i can wait till loading window close.

You should use implicit wait for this purpose. Add this statement for setting Implicit wait on driver object , after initialising the driver instance.
driver.manage().timeouts().implicitlyWait(Integer.parseInt("30"),TimeUnit.SECONDS);

You can use this :
wait.until(ExpectedConditions.visibilityOfElementLocated(webElement));
webElement.click();

You can write you personal waiter. I guess, you will got a few cases when you will see this scroller. For example you can try use next approach:
public void waitIfScrollerStillVisibe(int seconds, By locator) {
int counter = 0;
while (!isElemenyVisible(locator)) {
if (counter == seconds) {
new throw ElementIsNotVisibleException();
}
else {
Thread.sleep(seconds);
counter++;
}
}
}

Related

How to Deal with ElementNotFound Exception in Selenium WebDriver

Overview : I have already prepared the automation script in Selenium Web driver script in Java which will login into a website and make the selections automatically and once the selections are completed it will run the report.
What I want : I am facing issue while optimizing my automation script.
Brief Explanation : Actually I am familiar with different kinds of wait we are using in Selenium but all those wait i.e implicit,explicit or fluent wait didn't able to help me out in making the code more optimized.Currently I am using Thread.sleep() method everywhere in order to run the script completely without any fail but I know this should not be best practice to be get followed because sometime Elements loads fast and sometime slow because of that either my Script execution took long time or failed based on Element availability.I created one separate method for Webdriver wait and Which I can call for various webelements whenever I needed in my main script but this approach also sometime works or sometime not even though I am passing 800 Second as Time period to wait but if I use Thread.sleep(5000) it will work without any issue not sure why ??
What I want to be have a separate method for wait which can be called in main script whenever required and I want my script to be worked flawless the moment webeelment visible just like what we human do when we interacting with any web.
Note : I have tried ExpectedCondition methods like elementtobeclickable, visibilityOfElementLocated,presenceofElementLocated all of them sometime these work but sometime won't.
Separate Method of wait I have created
public static WebElement waiting(WebDriver driver,String path){
WebDriverWait wait = new WebDriverWait(driver,800);
WebElement element=wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(path)));
return element;
}
Piece of main code where I am calling this Method.
if(nam.equals("Some name"))
{
WebElement e=driver.findElement(By.xpath("1st Webelement path"));
e.click();
System.out.println("Value clicked under First Drop Down is:"+e);
Listing.waiting(driver,"2nd WebElement xpath").click();
//Thread.sleep(5000);
//driver.findElement(By.xpath("2nd WebElement xpath")).click();
System.out.println("Second Dropdown clicked");
}
When I commenting the Thread.sleep() then it will throw the ElementNotFound exception even though I have used 800 Seconds in Webdriver wait method but the moment I removed the comment from Thread.sleep() method it will work.
Kindly Help me in getting the reusable and useful wait method which I can call several times in my main code.
Thanks in Advance !!
This usually works for me (not FluentWait though):
WebDriverWait wait = new WebDriverWait(driver, TIMEOUT);
ExpectedCondition elementIsDisplayed = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver arg0) {
try {
webElement.isDisplayed();
return true;
}
catch (NoSuchElementException e ) {
return false;
}
catch (StaleElementReferenceException f) {
return false;
}
}
};
wait.until(elementIsDisplayed);
Of course, setup TIMEOUT with the amount of time you want to wait for the element to be found (that is in seconds).

Selenium stop page load as soon as expected element exist

I created few test cases on Selenium using Java. Unfortunately when I click an element on the page, before I could move on to any other action, I have to wait till the page loads.
I have tried driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);. Unfortunately this creates another problem. Even if the page loads, it waits 30 seconds before it started testing on the page.
What I found the best way is to send ESCAPE key to stop page load.
Is there anyway I could check if an element exists and when it does, send ESCAPE key to the browser to stop page load?
This part is bugging my mind as I have to wait till page loads before Java reads the next line of the code so I can't send ESCAPE key to browser till the page actually stops loading.
Edit
I have just tried using a new thread to do the job but it seems driver is completely locked out, can't do any process on it before page stops loading.
I'm out of ideas for the moment but I believe there should be a way.
Using timeouts() is causing whole test case to stop.
First I'd like to say this isn't a best practice. The selenium click method states that if the click triggers a page load, selenium will do its best to block until the page is loaded. Instead of clicking via the click method you could try sending the click event via JavaScript. Then wait for the element like normal.
You can try driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS); It is supposed to throw an error after timeout is over. I have never used it but maybe you can try and catch this error and continue with your test. But your page could end up in an unstable state with everything not loading and test interacts with elements.
I did it in C#, scenario is the same elsewhere.
Define driver like this:
var firefoxOptions = new FirefoxOptions();
firefoxOptions.PageLoadStrategy = PageLoadStrategy.None;
driver = new FirefoxDriver(firefoxOptions);
PageLoadStrategy.None means when open a URL, continue to next line regardless of the results and do not wait to load the page.
Usually, it takes some seconds to load a page and element appears, suppose I'm waiting for email_user element to appears:
int user_emailID = 0, popupAlert = 0;
do
{
float timeToWait = 0;
driver.Navigate().GoToUrl("https://stackoverflow.com");
do
{
await Task.Delay(500);
timeToWait += 0.5F;
user_emailID = driver.FindElements(By.XPath("//input[#id=\'user_email\']")).Count;
}
while (user_emailID == 0 && timeToWait < 10);
if (user_emailID == 1)
{
//Element exists now!do something and don't wait for page to load completely
}
}
while (user_emailID != 1);
More explanation: when open a URL, first loop check the presence of element every 0.5 second, if it appears, the loop stops. If after 10 seconds it couldn't find the element, the page will reloaded !!
Hope this get you the idea.
Remember, exception must not happen in your codes !!

Wait for a modal to disappear in Selenium 2.0

When my test run using a webdriver for Firefox I'll get modal exception after reaching an accept on an alert:
[Exception]: Modal dialog present
The tests however work fine when using IE webdriver. The problem seems to be that test scenario proceeds before the alert is completely closed. In other words it tried to do the following:
List<WebElement> l = driver.findElements(By.linkText("link"));
and a result I'll get modal exception.
Now wait.until(ExpectedConditions) as mentioned wait.until(ExpectedConditions.visibilityOf Element1 OR Element2) is good candidate. However I am not able to create a condition that returns true when alart disappears. How can I do that?
Edit: to clarify further, the problem is not waiting for the alert to appear (my implicit wait is working fine for that purpose). I do get the alert and apply the test on that however after I click accept on the alert, test goes on fast and tried to proceed with the next step while alert still present and throws the modal present exception. I have also tried the following to prevent that with out success.
driver.switchTo().defaultContent();
There is now default mechanism to wait for alert to appear/disappear but, we can write our own logic something like below instead of waiting for static amount of time (Thread.sleep(10000)).
waitForAlert(WebDriver driver)
{
int i=0;
while(i++<5)
{
try
{
Alert alert = driver.switchTo().alert();
alert.accept();
break;
}
catch(NoAlertPresentException e)
{
Thread.sleep(1000);
continue;
}
}
}
even I faced this problem in FF and I came over this by using a AUI. Try to use the below code to get your alert > accept it and then continue with rest of your code/test.
Actions action = new Actions (driver);
action.click(driver.findElement(By.id("locator"))).build().perform();
driver.switchTo().alert().accept();
// Continue with your test
List<WebElement> l = driver.findElements(By.linkText("link"));

Is using the method driver.close() required?

Let's say
I have a window 1. I have performed an event on the window 1 that makes window 2 to appear.
Now I switched to the window 2 and clicked a button on it which closes window 2.
If I use driver.close() after I performed an event which caused the window to close, sometimes it throws NoSuchWindowException.
If I don't use the driver.close() then sometimes driver.getWindowHandles().size() returns 2 even when there is only one window and I have waited enough time to number of windows become 1.
I refresh driver.getWindowHandles() and check for the driver.getWindowHandles().size() to become 1 but it doesn't sometimes.
My question is, do I need to use the method driver.close() after I clicked the button that caused the window to close? How to use the driver.close() correctly.
EDIT: Yes, it is a problem. If selenium doesn't realize window2 has been closed, it keeps returning the handles to be 2. Suppose that I closed window2 and switched back to window1 and performed an event which opens window3. Now I want to switch to window3. Here is the problem because Selenium still think windows2 exists and now there are three windows according to the Selenium.
String window1Handle = driver.getWindowHandle();
//Now I have oepend window3
//According to the Selenium there are 3 windows
// So driver.getWindowHandles().size() returns 3
for (String window : driver.getWindowHandles() {
if (!window.equals(window1Handle)) {
driver.switchTo().window();
The above line may throw exception because driver is trying to switch to a window which has already been closed"
No you don't need to perform a driver.close(), if anything is left open, when you perform a driver.quit() at the end of your test WebDriver will clean up and make sure that everything is shut down correctly.
Selenium can track how many windows are open, if you are seeing window handles for windows that are closed that sounds like a potential bug. Bear in mind that it may take some time for Selenium to realise that the window has been closed, you could try using an explicit wait to wait for the count of window handles to drop back down to 1, you'll need to add the following ExpectedCondition:
public static ExpectedCondition<Boolean> numberOfWindowsToBe(final int numberOfWindows) {
return new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driver) {
return driver.getWindowHandles().size() == numberOfWindows;
}
};
}
Then you can use it by doing:
WebDriverWait wait = new WebDriverWait(driver, 15, 100);
wait.until(numberOfWindowsToBe(1));
or you could just try closing the window by performing a driver.close() and catching the NoSuchWindowException e.g.
try{
driver.close();
} catch(NoSuchWindowException ignored){
System.out.println("Window already closed");
}
This should give Selenium the kick it needs to realise that the window has been closed (Although to be honest I wouldn't bother).
*EDIT*
So it sounds like the problem is that you have multiple window handles and you don't know which one is the window that has been closed, and which one is your newly opened window. One workaround would be to track the window handles in a Map. Every time you open a new window store the window handle in the map like this:
Map<String, String> openedWindows = new HashMap<String, String>();
openedWindows.put("Window 1", driver.getWindowHandle());
You will then know which window handle is associated with your window, you can then remove windows from the map as they are closed. You will know which handles that are still being reported are actually closed and which are being reported in error.
Really this sounds like a bug in Selenium window handling and I would suggest you raise an issue on the issue tracker with a minimal test script that reproduces the problem. Of course the other option above is still valid, try and close the window but catch the exception and see if that gives Selenium the kick it needs to remove it from the list of window handles.
I had the same exact issue You are facing.
Before i perform an action which pops up second window, i intiated
String window = driver.getWindowHandle();
Later i clicked link 1 which populates window 2 and i switch to that window
driver.switchTo().window(window name);
i performed my action in Window 2 and when i click the link in Window 2 my window closes automatically and if i use driver.close() it wont happen as webdriver will throw error as u said
so instead of trying to close the second window, i try to switch back to window 1 with
driver.switchTo().window(window);
This is because since window 2 is closed automatically and since the control does not pass to window 1 the error will happen.. So there is no necessity to close window 2. instead we can switch back to our default window and continue or close the default window..
I know that this is a bit of a hack...but I've never seen something like what you are describing, so I think its worth a try. Change this code:
driver.switchTo().window();
to something like this:
try{
driver.switchTo().window();
perform action that will throw error
return; //will return if error wasn't thrown
catch(Error thrown if on bad window){
//continue in your for loop to switch to the next window;
}
I wrote a method that is working pretty good for me.
public static boolean letWebDriverRealizeThisWindowHasBeenClosed(WebDriver driver,
String closedWindowHandle) {
/**
* to avoid infinite loop, do write a break when definite time has been passed
*/
/**
* Generally, this method returns true given that window is closed
*/
boolean isWebDriverRealized = false;
long start = System.currentTimeMillis();
long end = start + (30 * 1000); //30 seconds
while (!isWebDriverRealized
&& System.currentTimeMillis() < end) {
try {
driver.switchTo().window(closedWindowHandle);
} catch (NoSuchWindowException nswe) {
isWebDriverRealized = true;
}
}
return isWebDriverRealized;
}
If this method returns true, then it means WebDriver has realized that window has been closed. driver.getWindowHandles.size() returns the correct number of windows once the above method returns true.
No, you don't need to do that. Because second window is already close, and if you will use method driver.close() it will close your first window and the browser itself(because there is only one tab left in browser window).
Its depends upon the Window,
some Window close while click on outside Window content, in that case no need of driver.close() method.
but for some Window, click on outside the Window content, Window unable to close (i.e. Window gets close after click on close button), in that case need to close such Window using thedriver.close() method.

How do I click on an image button in WebDriver using Java?

The button type is image, and the relevant code in HTML code attached. I have entered all the data and clicked on Apply Now button, it is not at all saving. But when I try to create it manually, it is saved in less than 15 seconds.
Please find the attached screen shot.
The relevant code for the same:
//Navigating to Quick Application
driver.get(QAurl);
Thread.sleep(15000);
driver.findElement(By.id("DdlSalesPerson")).sendKeys("Swamy m Kumara");
driver.findElement(By.id("TxtFName")).sendKeys("Kumar");
driver.findElement(By.id("TxtLName")).sendKeys("Swamy");
driver.findElement(By.id("TxtAddress")).sendKeys("434, Main Road, Somajiguda");
driver.findElement(By.id("TxtZip")).sendKeys("79081");
driver.findElement(By.id("TxtSSN1")).sendKeys("881");
Thread.sleep(15000);
driver.findElement(By.id("TxtSSN2")).sendKeys("72");
driver.findElement(By.id("TxtSSN3")).sendKeys("4365");
Thread.sleep(5000);
driver.findElement(By.id("TxtDayPhone1")).sendKeys("963");
driver.findElement(By.id("TxtDayPhone2")).sendKeys("210");
driver.findElement(By.id("TxtDayPhone3")).sendKeys("5478");
Thread.sleep(5000);
driver.findElement(By.id("ChkIAgree")).click();
driver.findElement(By.id("TxtSignature")).sendKeys("Kumar Swamy");
Thread.sleep(5000);
System.out.println("Entered all the required fields");
//Reading the value in the image.
WebElement element = driver.findElement(By.id(OR.getProperty("FP_SImg_ID")));
String src = ((JavascriptExecutor)driver).executeScript("return arguments[0].attributes['src'].value;", element).toString();
img =src.split("=");
System.out.println("Value retrieved from the Image source: "+img[1]);
driver.findElement(By.id(OR.getProperty("FP_TxtSImg_ID"))).sendKeys(img[1]);
Thread.sleep(5000);
driver.findElement(By.id("TxtEmailId")).sendKeys("abc#abc.com");
driver.findElement(By.name("BtnSubmit")).click();
Thread.sleep(35000);
System.out.println("Successfully Applied from the QuickApp");
HTML code for the Apply now button:
<input id="BtnSubmit" type="image" style="height:33px;width:121px;border-width:0px;"
onclick="javascript:return validateControls();" src="../Common/Images/HybridQA
/apply_now.png" title="Submit Here" tabindex="45" name="BtnSubmit">
Any help will be appreciated.
You have 1 minute 25 seconds of Thread.sleep() in your code...
Remove all the thread.sleep(), if you are waiting for elements to appear do it properly, use an explicit wait:
http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp
To take an example from the page linked above:
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));
Have a look at the ExpectedConditions class to see the available conditions built into selenium, if they don't meet your needs it's trivial to write your own expected conditions.
-------------------Edit-------------------
For the record this answer is for the original question that was asked which is quoted below (you can have a look at the edit history of the original question to verify this as well).
Taking long time to save after clicking on Apply Now button using Webdriver in Java
Taking long time to save after clicking on Apply Now button using
Webdriver in Java. I have entered all the data and clicked on Apply
now button, it is not at all saving. But when i try to create it
manually, it is saved in less than 15 seconds. Please find the
attached screen shot.
There could be 2 reasons for this problem.
One is from the HTML code of 'Apply Now' button, I could see that it shows as "input
id='BtnSubmit'", but in your script its written as
'driver.findElement(By.name("BtnSubmit")).click();'.
Shouldn't it be "driver.findElement(By.id("BtnSubmit")).click()"?; 'name' must be
replaced with 'id'.
At the end of the script you click 'BtnSubmit', the session might expire immediately after
you click that button. This problem usually occurs when you use an older and new version
of selenium standalone jar file. See to that you use only the latest version and not in
addition to an old version.
Use this,
driver.findElement(By.id("TxtEmailId")).sendKeys(Keys.ENTER);
after this,
driver.findElement(By.id("TxtEmailId")).sendKeys("abc#abc.com");
and comment,
driver.findElement(By.name("BtnSubmit")).click();
So your code looks like,
driver.findElement(By.id("TxtEmailId")).sendKeys("abc#abc.com");
driver.findElement(By.id("TxtEmailId")).sendKeys(Keys.ENTER);
//driver.findElement(By.name("BtnSubmit")).click();
Sometimes it's difficult to handle image buttons because these buttons are activated when all required fields are entered. Make sure you filled all mandatory fields and press enter after entering last field in the form. First try to do it manually. Instead of clicking on button press enter at last input field and use same stratefy with automation.
Update:
Use your own code and replace Thread.sleep() with below method.
Call it like,
waitForElementToBePresent(By.id("DdlSalesPerson"), 15000);
It waits for next element whichever you pass as argument. It returns true if found or false if not. If element found within the given time it will return true immediately instead of waiting for given time.
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;
}

Categories