Pavel Janicek
Pavel Janicek

Reputation: 14748

Best way to automate loop in Selenium

I would like to automate some repetitive task - say submitting some form more than once. I am stumbling on the page load issues, so I want you to ask you how do you do it. Say, I want to submit ten different entries to our form. so I can do something like this:

for (int i =0; i<10; i++){
  String name = getNextName();
  String surname = getNextSurname();
  Webelement newUserButton = driver.findElement(By.id("newUser")));
  newUserButton.click();
  WebElement name = driver.findElement(By.id("name")));
  name.sendKeys(name);
  WebElement surname = driver.findElement(By.id("surname")));
  surname.sendKeys(surname);
  WebElement submit = driver.findElement(By.id("submit")));
  submit.click();
}

But I found out that if my test environment is slowlier, the above loop can crash. I tried to add some Thread.sleep() to the code, but if I want so submit, say, 200 entries, it can be really long to do the script.

Is there any function which can wait only the time when the form is ready?

Upvotes: 1

Views: 6699

Answers (2)

Hari Reddy
Hari Reddy

Reputation: 3858

If you are using Selenium 2.0 you can make the WebDriver to wait until some action takes place by creating a WebDrivewWait object in you code. You can check out this link for more info - http://selenium.googlecode.com/svn/trunk/docs/api/java/index.html

Upvotes: 1

Justin Ko
Justin Ko

Reputation: 46836

Sounds like you need to add an explicit wait - see the Webdriver page Advanced Usage - Explicit and Implicit Waits

With the explicit waits, you can tell webdriver to wait until the form is in the ready state - typically a certain field is visible or reset (depends on what happens to your form when you click submit).

Upvotes: 2

Related Questions