java: Sleep until website is fully loaded

10,637

Solution 1

Selenium has already timeouts for this.

Look here: http://seleniumhq.org/docs/04_webdriver_advanced.jsp

I have solve it with:

webDriver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

Solution 2

Prefer explicit waits:
1) more readable
2) been using those for long time
3) what if you know the element is not there (your test is to verify it) and don't need to poll for 10 seconds? With implicit you are now wasting time.

WebElement myDynamicElement = (new WebDriverWait(driver, 10))
  .until(new ExpectedCondition<WebElement>(){
    @Override
    public WebElement apply(WebDriver d) {
        return d.findElement(By.id("myDynamicElement"));
    }});
Share:
10,637
Michael
Author by

Michael

Updated on August 06, 2022

Comments

  • Michael
    Michael almost 2 years

    I want to open a website with selenium and extract some text via xpath. It's working but I can get the text only if I wait a few seconds until the whole website is loaded, but it would be nicer to check if the website is fully loaded. I guess I should check for any background connections (ajax calls, GETs, POSTs or whatever), what is the best way to do it? At the moment I'm trying to extract the text in a while loop (ugly solution):

    WebDriver driver = new FirefoxDriver();
    driver.get("http://www.website.com");
    
    
    // Try to get text
     while (true) {
       try {
         WebElement findElement = driver.findElement(By.xpath("expression-here"));
         System.out.println(findElement.getText());
         break;
    // If there is no text sleep one second and try again
       } catch (org.openqa.selenium.NoSuchElementException e) {
         System.out.println("Waiting...");
         Thread.sleep(1000);
       }
     }
    

    How would you solve this?