I posed with a difficult task. I am fairly new to selenium and still working through the functionalities of waiting for elements and alike.
I have to manipulate some data on a website and then proceed to another. Problem: the manipulation invokes a script that makes a little "Saving..." label appear while the manipulated data is being processed in the background. I have to wait until I can proceed to the next website.
So here it is:
How do i wait for and element to DISAPPEAR? Thing is: It is always present in the DOM but only made visible by some script (I suppose, see image below).
This is what I tried but it just doesn't work - there is no waiting, selenium just proceeds to the next step (and gets stuck with an alert asking me if I want to leave or stay on the page because of the "saving...").
private By savingLableLocator = By.id("lblOrderHeaderSaving");
public boolean waitForSavingDone(By webelementLocator, Integer seconds){
WebDriverWait wait = new WebDriverWait(driver, seconds);
Boolean element = wait.until(ExpectedConditions.invisibilityOfElementLocated(webelementLocator));
return element;
}
UPDATE / SOLUTION:
I came up ith the following solution: I built my own method. Basically it checks in a loop for the CssValue to change.
the loops checks for a certain amount of time for the CSSVALUE "display" to go from "block" to another state.
public void waitForSavingOrderHeaderDone(Integer _seconds){
WebElement savingLbl = driver.findElement(By.id("lblOrderHeaderSaving"));
for (int second = 0;; second++) {
if (second >= _seconds)
System.out.println("Waiting for changes to be saved...");
try {
if (!("block".equals(savingLbl.getCssValue("display"))))
break;
} catch (Exception e) {
}
}
You can wait for a WebElement to throw a StaleElementReferenceException like this:
public void waitForInvisibility(WebElement webElement, int maxSeconds) {
Long startTime = System.currentTimeMillis();
try {
while (System.currentTimeMillis() - startTime < maxSeconds * 1000 && webElement.isDisplayed()) {}
} catch (StaleElementReferenceException e) {
return;
}
}
So you would pass in the WebElement you want to wait for, and the max amount of seconds you want to wait.
Webdriver has built in waiting functionality you just need to build in the condition to wait for.
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return (driver.findElements(By.id("lblOrderHeaderSaving")).size() == 0);
}
});
I'm not sure, but you can try something like this :)
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //time in second
WebElement we = driver.findElement(By.id("lblOrderHeaderSaving"));
assertEquals("none", we.getCssValue("display"));
This works with selenium 2.4.0. you have to use the invisibility mehtod to find it.
final public static boolean waitForElToBeRemove(WebDriver driver, final By by) {
try {
driver.manage().timeouts()
.implicitlyWait(0, TimeUnit.SECONDS);
WebDriverWait wait = new WebDriverWait(UITestBase.driver,
DEFAULT_TIMEOUT);
boolean present = wait
.ignoring(StaleElementReferenceException.class)
.ignoring(NoSuchElementException.class)
.until(ExpectedConditions.invisibilityOfElementLocated(by));
return present;
} catch (Exception e) {
return false;
} finally {
driver.manage().timeouts()
.implicitlyWait(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
}
}
I used following C# code to handle this, you may convert it to Java
public bool WaitForElementDisapper(By element)
{
try
{
while (true)
{
try
{
if (driver.FindElement(element).Displayed)
Thread.Sleep(2000);
}
catch (NoSuchElementException)
{
break;
}
}
return true;
}
catch (Exception e)
{
logger.Error(e.Message);
return false;
}
}
You can also try waiting for the ajax calls to complete. I've used this to check when the page load is complete and all the elements are visible.
Here's the code - https://stackoverflow.com/a/46640938/4418897
You could use XPath and WebDriverWait to check whether display: none is present in the style attribute of an element. Here is an example:
// Specify the time in seconds the driver should wait while searching for an element which is not present yet.
int WAITING_TIME = 10;
// Use the driver for the browser you want to use.
ChromeDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, WAITING_TIME);
// Replace ELEMENT_ID with the ID of the element which should disappear.
// Waits unit style="display: none;" is present in the element, which means the element is not visible anymore.
driver.wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#id='ELEMENT_ID'][contains(#style, 'display: block')]")));
Try using invisibilityOfElementLocated method.
You can reference example here How to wait until an element no longer exists in Selenium?
enter image description hereI created my own method for element disappearing from dom....
In Conditions class (In .m2\repository\org\seleniumhq\selenium\selenium-support\3.141.59\selenium-support-3.141.59.jar!\org\openqa\selenium\support\ui\ExpectedConditions.class)
we can see that 'isInvisible' method with 'isDisplayed' method,,, i wrote the same with 'isEnabled'
public static ExpectedCondition<Boolean> invisibilityOf(final WebElement element) {
return new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver webDriver) {
return isRemovedFromDom(element);
}
#Override
public String toString() {
return "invisibility of " + element;
}
};
}
private static boolean isRemovedFromDom(final WebElement element) {
try {
return !element.isEnabled();
} catch (StaleElementReferenceException ignored) {
return true;
}
}
Related
Hi i am working on a selenium project and the top difficulty that i am having was waiting for XHR request to be completed. What i am currently doing is i wait for a request to be made using following expected condition,
public ExpectedCondition<Boolean> jQueryExpect (int expectedActive) {
ExpectedCondition<Boolean> jQLoad = new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver dr) {
try {
logger.log(Level.INFO,"Checking number of jQueries Active");
Long active = (Long) ((JavascriptExecutor) driver).executeScript("return jQuery.active");
logger.log(Level.INFO,"jQuery''s active: {0}",active);
return (active >= expectedActive);
}
catch (Exception e) {
logger.log(Level.WARNING,"Error executing script in jQueryLoad method");
// no jQuery present
return true;
}
}
};
return jQLoad;
}
And then i wait for the jQuery to load using this expected condition
public ExpectedCondition<Boolean> jQueryLoad (int expectedActive) {
ExpectedCondition<Boolean> jQLoad = new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver dr) {
try {
logger.log(Level.INFO,"Checking number of jQueries Active");
Long active = (Long) ((JavascriptExecutor) driver).executeScript("return jQuery.active");
logger.log(Level.INFO,"jQuery''s active: {0}",active);
return (active <= expectedActive);
}
catch (Exception e) {
logger.log(Level.WARNING,"Error executing script in jQueryLoad method");
// no jQuery present
return true;
}
}
};
return jQLoad;
}
This method is working pretty solid for now since i know how many requests to expect. But as you have already noticed it can easily break in future as number of requests made are changed for some reason.
I been looking at cypress documentation and found this. According to cypress documentation this waits for the specified requests to be made.
cy.wait(['#getUsers', '#getActivities', '#getComments']).then((xhrs) => {
// xhrs will now be an array of matching XHR's
// xhrs[0] <-- getUsers
// xhrs[1] <-- getActivities
// xhrs[2] <-- getComments
})
Is there any such method available in Selenium? or Is there any way this can be implemented? So far from what i have googled i got nothing. So any help will be appreciated.
You can locate Element and wait for element
There are Implicit and Explicit waits in selenium.
You can use either
WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>));
or
wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>));
More information: on this answer
For this example let's look at the site pinterest:
When i make the initial login, there is a loading of pins.
In order to get more pins i need to scroll to the end of the page, after there is a request made for more pins (Lot's of sites are working like that i suppose)
So i know how to do the scroll in selenium, but how do i wait for the request to end?
I mean, it's not waiting for certain element to appear, the kind of element (The pins) is already there but i am waiting for others to appear.
If i use expected condition with wait, it good for the first batch of pins, but those that add to them, how do i wait for them, example:
When pinterest first load->
WebDriverWait driverWait = new WebDriverWait(cd, 10, 1000);
element = driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("thepins")));
Which is great for the initial loading, now i scroll to the bottom of the page
((JavascriptExecutor) cd).executeScript("window.scrollTo(0, document.body.scrollHeight)");
Now depends on the page, there is a loading to more pins(And sometimes not) i want to wait for them to load before i do another scroll.
What is the best approach to this situation?
The way I would do it is using the number of elements on the page. So for example you could do:
int pinCount = webDriver.findElements(By.xpath("thepins")).size();
At this point run your jsExecutor for the scroll, then:
webDriverWait.until(ExpectedConditions.numberOfElementsToBeMoreThan(By.xpath("thepins"),pinCount ));
I think the best way to handle this is by having class with all the possibilities, than you call it from where you need to wait and the code bellow will do the magic, works very well for me
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Waiter {
private static WebDriver jsWaitDriver;
private static WebDriverWait jsWait;
private static JavascriptExecutor jsExec;
//Get the driver
public static void setDriver (WebDriver driver) {
jsWaitDriver = driver;
jsWait = new WebDriverWait(jsWaitDriver, 45);
jsExec = (JavascriptExecutor) jsWaitDriver;
}
//Wait for JQuery Load
public static void waitForJQueryLoad() {
//Wait for jQuery to load
ExpectedCondition<Boolean> jQueryLoad = driver -> ((Long) ((JavascriptExecutor) jsWaitDriver)
.executeScript("return jQuery.active") == 0);
//Get JQuery is Ready
boolean jqueryReady = (Boolean) jsExec.executeScript("return jQuery.active==0");
//Wait JQuery until it is Ready!
if(!jqueryReady) {
System.out.println("JQuery is NOT Ready!");
//Wait for jQuery to load
jsWait.until(jQueryLoad);
} else {
System.out.println("JQuery is Ready!");
}
}
//Wait for Angular Load
public static void waitForAngularLoad() {
WebDriverWait wait = new WebDriverWait(jsWaitDriver,45);
JavascriptExecutor jsExec = (JavascriptExecutor) jsWaitDriver;
String angularReadyScript = "return angular.element(document).injector().get('$http').pendingRequests.length === 0";
//Wait for ANGULAR to load
ExpectedCondition<Boolean> angularLoad = driver -> Boolean.valueOf(((JavascriptExecutor) driver)
.executeScript(angularReadyScript).toString());
//Get Angular is Ready
boolean angularReady = Boolean.valueOf(jsExec.executeScript(angularReadyScript).toString());
//Wait ANGULAR until it is Ready!
if(!angularReady) {
System.out.println("ANGULAR is NOT Ready!");
//Wait for Angular to load
wait.until(angularLoad);
} else {
System.out.println("ANGULAR is Ready!");
}
}
//Wait Until JS Ready
public static void waitUntilJSReady() {
WebDriverWait wait = new WebDriverWait(jsWaitDriver,45);
JavascriptExecutor jsExec = (JavascriptExecutor) jsWaitDriver;
//Wait for Javascript to load
ExpectedCondition<Boolean> jsLoad = driver -> ((JavascriptExecutor) jsWaitDriver)
.executeScript("return document.readyState").toString().equals("complete");
//Get JS is Ready
boolean jsReady = (Boolean) jsExec.executeScript("return document.readyState").toString().equals("complete");
//Wait Javascript until it is Ready!
if(!jsReady) {
System.out.println("JS in NOT Ready!");
//Wait for Javascript to load
wait.until(jsLoad);
} else {
System.out.println("JS is Ready!");
}
}
//Wait Until JQuery and JS Ready
public static void waitUntilJQueryReady() {
JavascriptExecutor jsExec = (JavascriptExecutor) jsWaitDriver;
//First check that JQuery is defined on the page. If it is, then wait AJAX
Boolean jQueryDefined = (Boolean) jsExec.executeScript("return typeof jQuery != 'undefined'");
if (jQueryDefined == true) {
//Pre Wait for stability (Optional)
sleep(30);
//Wait JQuery Load
waitForJQueryLoad();
//Wait JS Load
waitUntilJSReady();
//Post Wait for stability (Optional)
sleep(30);
} else {
System.out.println("jQuery is not defined on this site!");
}
}
//Wait Until Angular and JS Ready
public static void waitUntilAngularReady() {
JavascriptExecutor jsExec = (JavascriptExecutor) jsWaitDriver;
//First check that ANGULAR is defined on the page. If it is, then wait ANGULAR
Boolean angularUnDefined = (Boolean) jsExec.executeScript("return window.angular === undefined");
if (!angularUnDefined) {
Boolean angularInjectorUnDefined = (Boolean) jsExec.executeScript("return angular.element(document).injector() === undefined");
if(!angularInjectorUnDefined) {
//Pre Wait for stability (Optional)
sleep(30);
//Wait Angular Load
waitForAngularLoad();
//Wait JS Load
waitUntilJSReady();
//Post Wait for stability (Optional)
sleep(30);
} else {
System.out.println("Angular injector is not defined on this site!");
}
} else {
System.out.println("Angular is not defined on this site!");
}
}
//Wait Until JQuery Angular and JS is ready
public static void waitJQueryAngular() {
waitUntilJQueryReady();
waitUntilAngularReady();
}
public static void sleep (Integer seconds) {
long secondsLong = (long) seconds;
try {
Thread.sleep(secondsLong);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
If you know how many pins will show up in total, you can use:
// new wait 30 seconds
WebDriverWait wait30s = new WebDriverWait(driver,30);
wait30s.until(ExpectedConditions.numberOfElementsToBe("THIS LOCATOR MUST FIT TO ALL PINS", number));
// or
wait30s.until(ExpectedConditions.numberOfElementsToBeMoreThan("THIS LOCATOR MUST FIT TO ALL PINS", number));
I have been using thread.sleep(9000) almost after every line of code in selenium which is making me wait for long.Can anybody suggest me an alternate way to reduce this.As my application is taking time load a page it needs to wait until a particular page is loaded to perform any action.
WebElement un = driver.findElement(By.id("login_username_id"));
un.sendKeys(username);
WebElement pwd = driver.findElement(By.id("login_password_id"));
pwd.sendKeys(password);
try {
Thread.sleep(25000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
driver.findElement(By.id("login_submit_id")).click();
try {
Thread.sleep(9000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I want to reduce the usage of thread.sleep after every line and use one common function so that it waits whenever required.
use the below example:
public class Main{
static WebDriver driver = new FirefoxDriver();
public static void main(String [] args) throws InterruptedException{
WebElement un = driver.findElement(By.id("login_username_id"));
un.sendKeys(username);
WebElement pwd = driver.findElement(By.id("login_password_id"));
pwd.sendKeys(password);
waitForElement(By.id("ur id"),60);
driver.findElement(By.id("login_submit_id")).click();
waitForElement(By.id("ur id"),60);
}
/**
* wait until expected element is visible
*
* #param expectedElement element to be expected
* #param timeout Maximum timeout time
*/
public static void waitForElement(By expectedElement, int timeout) {
try {
WebDriverWait wait = new WebDriverWait(driver, timeout);
wait.until(ExpectedConditions.visibilityOfElementLocated(expectedElement));
} catch (Exception e) {
e.printStackTrace();
//System.out.println("print ur message here");
}
}
}
if u have any confusion, let me know.
Hi please use universal wait in your script i.e implicit wait
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
above line tell selenium to wait for maximum of 10 seconds for each and every webelement before throwing any error (note you can increase or decrease seconds it depends upon you)
explicit wait : when you want to wait for a specific webelement (use this when you think a particular element takes more then usual time to load then only)
WebDriverWait wait = new WebDriverWait(driver, timeout);
wait.until(ExpectedConditions.visibilityOfElementLocated(your element));
You can put assertion saying that "Whether particular element displayed or not" so that web driver will spend time to search that element which will create delay in execution.
Ex: A page may contain some button make it as target and tell web driver to find it.
I'm currently using PhantomJS + Selenium to populate some form fields but having weird results. 50% of the time, the test runs fine. The other 50% it errors out and gives me the following
{"errorMessage":"Element is not currently interactable and may not be
manipulated"
I'm doing the following to make sure the page is loaded.
private static boolean waitForJQueryProcessing(WebDriver driver,
int timeOutInSeconds) {
boolean jQcondition = false;
try {
new WebDriverWait(driver, timeOutInSeconds) {
}.until(new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driverObject) {
return (Boolean) ((JavascriptExecutor) driverObject)
.executeScript("return jQuery.active == 0");
}
});
jQcondition = (Boolean) ((JavascriptExecutor) driver)
.executeScript("return window.jQuery != undefined && jQuery.active === 0");
return jQcondition;
} catch (Exception e) {
logger.debug(e.getMessage());
}
return jQcondition;
}
And then to interact with the element(s):
pageWait.until(ExpectedConditions.presenceOfElementLocated(By
.cssSelector("#myForm-searchDate")));
driver.findElement(
By.cssSelector("#myForm-searchDate"))
.sendKeys(Keys.CONTROL + "a");
driver.findElement(
By.cssSelector("#myForm-searchDate"))
.sendKeys(Keys.DELETE);
driver.findElement(
By.cssSelector("#myForm-searchDate"))
.sendKeys(MY_TEST_DATE);
I could see if it failed all the time, but it doesn't fail all the time so it's hard to repeat the results when debugging.
Edit 1. I've tried swapping following the comment below; however, it doesn't work. I've since come to realize this seems to only happen when I fire up several (5+) instances of PhantomJS at once.
In webdriver, how to ask to webdriver to wait until text is present in text field.
actually i have one kendo text field whose values comes from database which takes some time to load. Once it load i can proceed further.
please help on this
You can use WebDriverWait. From docs example:
(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.findElement(...).getText().length() != 0;
}
});
You can use WebDriverWait. From docs example:
above ans using .getTex() this is not returning text from input field
use .getAttribute("value") instead of getText()
(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.findElement(...).getAttribute("value").length() != 0;
}
});
tested
100% working
hope this will help
A one liner that works and uses lambda function.
wait.until((ExpectedCondition<Boolean>) driver -> driver.findElement(By.id("elementId")).getAttribute("value").length() != 0);
Using WebDriverWait (org.openqa.selenium.support.ui.WebDriverWait) and ExpectedCondition (org.openqa.selenium.support.ui.ExpectedConditions) objects
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.id("element_id"), "The Text"));
You can use a simple method in which you need to pass driver object webelement in which text is going to come and the text which is goint to come.
public static void waitForTextToAppear(WebDriver newDriver, String textToAppear, WebElement element) {
WebDriverWait wait = new WebDriverWait(newDriver,30);
wait.until(ExpectedConditions.textToBePresentInElement(element, textToAppear));
}
This is my solution for sending text to input:
public void sendKeysToElement(WebDriver driver, WebElement webElement, String text) {
WebDriverWait wait = new WebDriverWait(driver, Configuration.standardWaitTime);
try {
wait.until(ExpectedConditions.and(
ExpectedConditions.not(ExpectedConditions.attributeToBeNotEmpty(webElement, "value")),
ExpectedConditions.elementToBeClickable(webElement)));
webElement.sendKeys(text);
wait.until(ExpectedConditions.textToBePresentInElementValue(webElement, text));
activeElementFocusChange(driver);
} catch (Exception e) {
Configuration.printStackTraceException(e);
}
}
WebElement nameInput = driver.findElement(By.id("name"));
sendKeysToElement(driver, nameInput, "some text");