Selenium Web Driver Wait For Long Time

Find the data you need here

We provide programming data of 20 most popular languages, hope to help you!

Previous PostNext Post

Selenium Web driver wait for long time

 driver.manage().timeouts().implicitlyWait(5, TimeUnit.MINUTES);
WebDriverWait wait = new WebDriverWait(driver, 300); // The int here is the maximum time in seconds the element can wait.
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("someId")));

How to use Wait commands in Selenium WebDriver

Here, the reference variable is named <wait> for the <WebDriverWait> class. It is instantiated using the WebDriver instance. The maximum wait time must be set for the execution to layoff. Note that the wait …

import java.util.concurrent.TimeUnit;
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Package waitExample;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class WaitTest {

private WebDriver driver;
private String baseUrl;
private WebElement element;

@BeforeMethod
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://www.google.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

@Test
public void testUntitled() throws Exception {
driver.get(baseUrl);
element = driver.findElement(By.id("lst-ib"));
element.sendKeys("Selenium WebDriver Interview questions");
element.sendKeys(Keys.RETURN);
List<WebElement> list = driver.findElements(By.className("_Rm"));
System.out.println(list.size());

}

@AfterMethod
public void tearDown() throws Exception {
driver.quit();
}
}
import org.openqa.selenium.support.ui.ExpectedConditions
import org.openqa.selenium.support.ui.WebDriverWait
WebDriverWait wait = new WebDriverWait(driver,30);
package waitExample;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class ExpectedConditionExample {
// created reference variable for WebDriver
WebDriver driver;

@BeforeMethod
public void setup() throws InterruptedException {

// initializing driver variable using FirefoxDriver
driver=new FirefoxDriver();
// launching gmail.com on the browser
driver.get("https://gmail.com");
// maximized the browser window
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}

@Test
public void test() throws InterruptedException {
// saving the GUI element reference into a "element" variable of WebElement type
WebElement element = driver.findElement(By.id("Email"));
// entering username
element.sendKeys("[email protected]");
element.sendKeys(Keys.RETURN);
// entering password
driver.findElement(By.id("Passwd")).sendKeys("password");
// clicking signin button
driver.findElement(By.id("signIn")).click();
// explicit wait - to wait for the compose button to be click-able
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(),'COMPOSE')]")));
// click on the compose button as soon as the "compose" button is visible
driver.findElement(By.xpath("//div[contains(text(),'COMPOSE')]")).click();
}

@AfterMethod
public void teardown() {
// closes all the browser windows opened by web driver
driver.quit();
}

}
Wait wait = new FluentWait(WebDriver reference)
.withTimeout(timeout, SECONDS)
.pollingEvery(timeout, SECONDS)
.ignoring(Exception.class);

WebElement foo=wait.until(new Function<WebDriver, WebElement>() {
public WebElement applyy(WebDriver driver) {
return driver.findElement(By.id("foo"));
}
});
//Declare and initialise a fluent wait
FluentWait wait = new FluentWait(driver);
//Specify the timout of the wait
wait.withTimeout(5000, TimeUnit.MILLISECONDS);
//Sepcify polling time
wait.pollingEvery(250, TimeUnit.MILLISECONDS);
//Specify what exceptions to ignore
wait.ignoring(NoSuchElementException.class)

//This is how we specify the condition to wait on.
//This is what we will explore more in this chapter
wait.until(ExpectedConditions.alertIsPresent());
driver.manage().timeouts().pageLoadTimeout(100, SECONDS);
driver.manage().timeouts().setScriptTimeout(100,SECONDS);
thread.sleep(1000);

Selenium Easy

We can use WebDriverWait class in many different cases. When ever we need to perform any operation on element, we can use Webdriver wait to check if the element is Present or visible or enabled or disabled or Clickable etc. NOTE - There are changes with Waits and Timeouts in Selenium 4, please check Updated Webdriver waits and timeouts. We will look …

WebDriverWait wait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.presenceOfElementLocated(locator)); 
WebElement element = driver.findElements(By.cssSelector(""));
element.size()>0;
WebDriverWait wait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.elementToBeClickable(locator));
WebDriverWait wait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
WebDriverWait wait = new WebDriverWait(driver, waitTime);
 wait..until(ExpectedConditions.visibilityOf(element));
List<WebElement> linkElements = driver.findelements(By.cssSelector('#linkhello'));
WebDriverWait wait = new WebDriverWait(driver, waitTime);
 wait..until(ExpectedConditions.visibilityOfAllElements(linkElements));
WebDriverWait wait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.invisibilityOfElementLocated(locator)); 
WebElement element = driver.findElement(By.id(""));
element.isEnabled();
WebElement element = driver.findElement(By.id(""));
element.isDisplayed();
WebDriverWait wait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.invisibilityOfElementWithText(by));
WebDriverWait wait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.invisibilityOfElementWithText(by, strText));

How to Use Selenium WebDriver Waits using Python

Following is the code snippet demonstrating the Explicit wait. In the above script, the timeout value is 10 seconds. It means the Webdriver will wait for 10 …

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.implicitly_wait(100)

driver.get("http://google.com")
driver.maximize_window()

print("Implicit Wait Example")

inputElement = driver.find_element_by_id("lst-ib")
inputElement.send_keys("Techbeamers")
inputElement.submit()

driver.close()
<body bgcolor="#C0C0C0">
<h1>Simple Alert Demonstration</h1>
<p>
Press button underneath to generate an alert.
</p>
<button onclick="alertFunction()" name ="alert">Generate Alert</button>
<script>
function alertFunction() {
    alert("Hello! I'm a Simple Alert.\nPlease press the 'OK' button.");
}
</script>
</body>
</html>
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as cond
from selenium.common.exceptions import NoAlertPresentException
from selenium.common.exceptions import TimeoutException

driver = webdriver.Firefox()
driver.maximize_window()
#location = "file://<Specify Path to Simple_Alert.HTML>"
location = "file://C:/Users/Automation-Dev/Desktop/Meenakshi/Selenium%20Python/Simple_Alert.HTML"
driver.get(location)

#Press the "Alert" button to demonstrate the Simple Alert
button = driver.find_element_by_name('alert')
button.click()

try:
    # Wait as long as required, or maximum of 10 sec for alert to appear
    WebDriverWait(driver,10).until(cond.alert_is_present())

    #Change over the control to the Alert window
    obj = driver.switch_to.alert

    #Retrieve the message on the Alert window
    msg=obj.text
    print ("Alert shows following message: "+ msg )
    
    #Use the accept() method to accept the alert
    obj.accept()

except (NoAlertPresentException, TimeoutException) as py_ex:
    print("Alert not present")
    print (py_ex)
    print (py_ex.args)
finally:
    driver.quit()

Selenium WebDriver - Wait for long running queues

Selenium WebDriver - Wait for long running queues. Ask Question Asked 2 years, 8 months ago. Modified 2 years, You can also convert this code into a while loop if you would like to start a WebDriver instance to check the queue on a time interval. For example, if the queue takes 12-16 hours to finish, you may want to wait 12 hours, then

public class DriverManager
{

    public IWebDriver CreateDriver
    {
        // code to initialize your WebDriver instance here
    }

    public void CloseWebDriverSession
    {
        Driver.Close();
        Driver.Quit();
    }
}
public class TestBothQueues
{
    // this driver instance will keep track of your session throughout the test case
    public IWebDriver driver;

    [Test]
    public void ShouldRunBothQueues
    {
        // declare instance of DriverManager class
        DriverManager manager = new DriverManager();    

        // start a webdriver instance
        driver = manager.CreateDriver();

        // run the first queue
        RunFirstQueue();

        // terminate the WebDriver so we don't have browser open for 12 hours
        manager.CloseWebDriverSession();

        // wait 12 hours
        Thread.Sleep(TimeSpan.FromHours(12));

        // start another WebDriver session to start the second queue
        driver = manager.CreateDriver();

        // run the second queue
        RunSecondQueue();

        // terminate when we are finished
        manager.CloseWebDriverSession();
    }
}

// first, wait initial 12 hours
Thread.Sleep(TimeSpan.FromHours(12));

// keep track of whether or not queue is finished
bool isQueueFinished = false;

while (!isQueueFinished);
{

    // start webdriver instance to check the queue
    IWebDriver driver = manager.CreateDriver();

    // check if queue is finished
    isQueueFinished = CheckIfQueueFinished(driver);

    // if queue is finished, while loop will break
    // if queue is not finished, close the WebDriver instance, and start again

    if (!isQueueFinished)
    {
        // close the WebDriver since we won't need it
        manager.CloseWebDriverSession();

        // wait another hour
        Thread.Sleep(TimeSpan.FromHours(1));
    }
}
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
// You need to import the following class - import java.util.concurrent.TimeUnit;
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(15));
//Import these two packages:
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

//Declare a WebDriverWait variable. In this example, we will use myWaitVar as the name of the variable.
WebDriverWait myWaitVar = new WebDriverWait(driver, 30);

//Use myWaitVar with ExpectedConditions on portions where you need the explicit wait to occur. In this case, we will use explicit wait on the username input before we type the text tutorial onto it.
myWaitVar.until(ExpectedConditions.visibilityOfElementLocated(By.id(“username”)));
driver.findElement(By.id(“username”)).sendKeys(“tutorial”);
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.PhantomJS;

// You can use any other WebDriver you want, such as ChromeDriver.
using (var driver = new PhantomJSDriver())
{
    driver.Navigate().GoToUrl("http://somedomain/url_that_delays_loading");

    // We aren't going to use it more than once, so no need to declare this a variable.
    new WebDriverWait(driver, TimeSpan.FromSeconds(10))
        .Until(ExpectedConditions.ElementIsVisible(By.Id("element-id")));

    // After the element is detected by the previous Wait, 
    // it will display the element's text
    Console.WriteLine(driver.FindElement(By.Id("element-id")).Text);
}
Wait wait = new FluentWait(driver).withTimeout(30, SECONDS).pollingEvery(2, SECONDS).ignoring(NoSuchElementException.class);


WebElement testElement = wait.until(new Function() {
    public WebElement apply(WebDriver driver) {
        return driver.findElement(By.id("testId"));
    }
});

Implicit, Explicit and Fluent Wait in Selenium WebDriver

The Implicit Wait in Selenium is used to tell the web driver to wait for a certain amount of time before it throws a “No Such Element Exception”. The default setting is 0. Once we set the time, the web driver will wait for the element for that time before throwing an exception. Selenium Web Driver has borrowed the idea of implicit waits

driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);
package guru.test99;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class AppTest {
	
	protected WebDriver driver;
	@Test
	public void guru99tutorials() throws InterruptedException 
	{
	System.setProperty ("webdriver.chrome.driver",".\\chromedriver.exe" );
	driver = new ChromeDriver(); 
	driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS) ;
	String eTitle = "Demo Guru99 Page";
	String aTitle = "" ;
	// launch Chrome and redirect it to the Base URL
	driver.get("http://demo.guru99.com/test/guru99home/" );
	//Maximizes the browser window
	driver.manage().window().maximize() ;
	//get the actual value of the title
	aTitle = driver.getTitle();
	//compare the actual title with the expected title
	if (aTitle.equals(eTitle))
	{
	System.out.println( "Test Passed") ;
	}
	else {
	System.out.println( "Test Failed" );
	}
	//close browser
	driver.close();
}
}
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS) ;
WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);
package guru.test99;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;

public class AppTest2 {
	protected WebDriver driver;
	@Test
	public void guru99tutorials() throws InterruptedException 
	{
	System.setProperty ("webdriver.chrome.driver",".\\chromedriver.exe" );
	driver = new ChromeDriver(); 
	WebDriverWait wait=new WebDriverWait(driver, 20);
	String eTitle = "Demo Guru99 Page";
	String aTitle = "" ;
	// launch Chrome and redirect it to the Base URL
	driver.get("http://demo.guru99.com/test/guru99home/" );
	//Maximizes the browser window
	driver.manage().window().maximize() ;
	//get the actual value of the title
	aTitle = driver.getTitle();
	//compare the actual title with the expected title
	if (aTitle.contentEquals(eTitle))
	{
	System.out.println( "Test Passed") ;
	}
	else {
	System.out.println( "Test Failed" );
	}
	WebElement guru99seleniumlink;
	guru99seleniumlink= wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath( "/html/body/div[1]/section/div[2]/div/div[1]/div/div[1]/div/div/div/div[2]/div[2]/div/div/div/div/div[1]/div/div/a/i")));
	guru99seleniumlink.click();
	}
	
}
WebElement guru99seleniumlink;
guru99seleniumlink = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[1]/section/div[2]/div/div[1]/div/div[1]/div/div/div/div[2]/div[2]/div/div/div/div/div[1]/div/div/a/i")));
guru99seleniumlink.click();
Wait wait = new FluentWait(WebDriver reference)
.withTimeout(timeout, SECONDS)
.pollingEvery(timeout, SECONDS)
.ignoring(Exception.class);
Wait wait = new FluentWait(WebDriver reference)
.withTimeout(Duration.ofSeconds(SECONDS))
.pollingEvery(Duration.ofSeconds(SECONDS))
.ignoring(Exception.class);

package guru.test99;

import org.testng.annotations.Test;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;

public class AppTest3 {
	protected WebDriver driver;
	@Test
	public void guru99tutorials() throws InterruptedException 
	{
	System.setProperty ("webdriver.chrome.driver",".\\chromedriver.exe" );
	String eTitle = "Demo Guru99 Page";
	String aTitle = "" ;
	driver = new ChromeDriver();
	// launch Chrome and redirect it to the Base URL
	driver.get("http://demo.guru99.com/test/guru99home/" );
	//Maximizes the browser window
	driver.manage().window().maximize() ;
	//get the actual value of the title
	aTitle = driver.getTitle();
	//compare the actual title with the expected title
	if (aTitle.contentEquals(eTitle))
	{
	System.out.println( "Test Passed") ;
	}
	else {
	System.out.println( "Test Failed" );
		}
	
	Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)							
			.withTimeout(30, TimeUnit.SECONDS) 			
			.pollingEvery(5, TimeUnit.SECONDS) 			
			.ignoring(NoSuchElementException.class);
	WebElement clickseleniumlink = wait.until(new Function<WebDriver, WebElement>(){
	
		public WebElement apply(WebDriver driver ) {
			return driver.findElement(By.xpath("/html/body/div[1]/section/div[2]/div/div[1]/div/div[1]/div/div/div/div[2]/div[2]/div/div/div/div/div[1]/div/div/a/i"));
		}
	});
	//click on the selenium link
	clickseleniumlink.click();
	//close~ browser
	driver.close() ;
	}
}
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)							
	.withTimeout(30, TimeUnit.SECONDS) 			
	.pollingEvery(5, TimeUnit.SECONDS) 			
	.ignoring(NoSuchElementException.class);				
public WebElement apply(WebDriver driver) {
        return driver.findElement(By.xpath("/html/body/div[1]/section/div[2]/div/div[1]/div/div[1]/div/div/div/div[2]/div[2]/div/div/div/div/div[1]/div/div/a/i"));

Previous PostNext Post

Related code examples