Reputation: 103
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.
Upvotes: 1
Views: 2976
Reputation: 11
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.
Upvotes: 0
Reputation: 3004
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.
Upvotes: 2
Reputation: 2938
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));
Upvotes: 2