How to Ask the Selenium-Webdriver to Wait for Few Seconds in Java

How can I ask the Selenium-WebDriver to wait for few seconds in Java?

Well, there are two types of wait: explicit and implicit wait.
The idea of explicit wait is

WebDriverWait.until(condition-that-finds-the-element);

The concept of implicit wait is

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

You can get difference in details here.

In such situations I'd prefer using explicit wait (fluentWait in particular):

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 function returns your found web element.
From the documentation on fluentWait:
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

Usage of fluentWait in your case be the following:

WebElement textbox = fluentWait(By.id("textbox"));

This approach IMHO better as you do not know exactly how much time to wait and in polling interval you can set arbitrary timevalue which element presence will be verified through .
Regards.

Make selenium driver wait, on nothing, for x seconds

Simply do Thread.sleep(1000) to sleep for 1 second.

How do we make the Selenium WebDriver wait for a few seconds?

for c#:

public static void Wait(int TimeMS)
{
Thread.Sleep(TimeMS);
}

Wait for few seconds in selenium?

It seems the Java Selenium API has a method pause(long).

According to the documentation it takes a long which represents the amount of milliseconds to pause for.

   Actions actionobj = new Actions(fd1);        
actionobj.moveToElement(heatmap);
actionobj.pause(10000); //wait 10 seconds
actionobj.click(heatmap);
actionobj.perform();

imlicitlyWait() does not pause your code. It's a method to let Selenium always wait for a couple of seconds if a WebElement is not instantly found.

Note that pause() is deprecated. It's bad practice to manually pause your code. You should question yourself why you deem it necessary to pause your code. If you want to simulate a human who waits 10 seconds, it perfectly fine, if you want some other elements or javascript to finish loading, then you should consider using different methods.

Edit: and your code doesnt pause halfway (even if you'd use Thread.sleep()) because on Action.perform() the whole sequence is carried out, for you build the Actions object first, and then, on perform, you perform the whole sequence of actions put together.

selenium wait few second and run execute next line code

To make thread sleep:

Thread.sleep(5000);

But that is not a good decision to make such sleeps, as your tests will be very slow. Use webdriver waits instead:

WebDriverWait wait = new WebDriverWait(driver, 5000);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("xpathHere")));

It will wait until elementToBeClickable (or you can choose any other condition) and continue test execution. Otherwise, if a condition is not met during a timeout - exception will be thrown.

Update:
If you write UI regression tests using selenium + java, it's highly recommended to use Selenide framework. Here is 10 min start tutorial: https://vimeo.com/107647158

  • It's fully integrated with pure selenium
  • manages WebDriver on its own (if you want you can pass your WebDriver setup by WebDriverRunner.setWebDriver(driver);)
  • have really easy to use and read syntax, like this: $("#elementId").pressEnter().should(disappear);
  • and what is important on this topic - it has easy to use waits, like :
$(By.id("elId")).waitUntil(attribute("attr", "expectedValued"), 5000);
$(By.id("elId")).should(matchText("Text to match"));

So initial code:

driver.findElement(By.xpath(".//*[@id='username']")).clear();
driver.findElement(By.xpath(".//*[@id='username']")).sendKeys(value);
driver.findElement(By.xpath(".//*[@id='password']")).sendKeys("apple123");
driver.findElement(By.xpath("html/body/div[1]/div/divdiv/button")).click();

With Selenide will look like (all waits included):

$("#username").shouldBe(visible).setValue(value);
$("#password").shouldBe(visible).setValue("apple123");
$(By.xpath("html/body/div[1]/div/divdiv/button")).shouldBe(visible).setValue("apple123");

Make Selenium wait 10 seconds

All the APIs you have mentioned is basically a timeout, so it's gonna wait until either some event happens or maximum time reached.

set_page_load_timeout - Sets the amount of time to wait for a page load to complete before throwing an error. If the timeout is negative, page loads can be indefinite.

implicitly_wait - Specifies the amount of time the driver should wait when searching for an element if it is not immediately present.

set_script_timeout - Sets the amount of time to wait for an asynchronous script to finish execution before throwing an error. If the timeout is negative, then the script will be allowed to run indefinitely.

For more information please visit this page. (documention is for JAVA binding, but functionality should be same for all the bindings)

So, if you want to wait selenium (or any script) 10 seconds, or whatever time. Then the best thing is to put that thread to sleep.

In python it would be

import time 
time.sleep(10)

The simplest way to do this in Java is using

try {
Thread.sleep(10*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

Getting Selenium to pause for X seconds

You can locate an element that loads after the initial page loads and then make Selenium wait until that element is found.

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("ID")));

How can I ask Selenium WebDriver to wait for some time?

You can make sure that the employeeName text box is populated before you continue with execution with this code -

new WebDriverWait(driver,10).until(new ExpectedCondition<Boolean>() {

public Boolean apply(WebDriver driver) {
String text = driver.findElement(By.id("employeeName")).getText();
return !text.equals("");
}
});

Now this code checks if the text in the employeeName text box is blank or not. If it is blank the driver waits for 10 seconds or if some data gets populated in the text field due to the AJAX call then it continues with execution.

If this does not work can you post some of your code by which you are making the AJAX call.

How can I ask the Selenium-WebDriver to wait for few seconds after sendkey?

I would avoid at all cost using something like that since it slows down tests, but I ran into a case where I didn't had other choices.

public void Wait(double delay, double interval)
{
// Causes the WebDriver to wait for at least a fixed delay
var now = DateTime.Now;
var wait = new WebDriverWait(myWebDriver, TimeSpan.FromMilliseconds(delay));
wait.PollingInterval = TimeSpan.FromMilliseconds(interval);
wait.Until(wd=> (DateTime.Now - now) - TimeSpan.FromMilliseconds(delay) > TimeSpan.Zero);
}

It's always better to observe the DOM somehow, e.g.:

public void Wait(Func<IWebDriver, bool> condition, double delay)
{
var ignoredExceptions = new List<Type>() { typeof(StaleElementReferenceException) };
var wait = new WebDriverWait(myWebDriver, TimeSpan.FromMilliseconds(delay)));
wait.IgnoreExceptionTypes(ignoredExceptions.ToArray());
wait.Until(condition);
}

public void SelectionIsDoneDisplayingThings()
{
Wait(driver => driver.FindElements(By.ClassName("selection")).All(x => x.Displayed), 250);
}


Related Topics



Leave a reply



Submit