Kemeeda
Kemeeda

Reputation: 123

Wait + refresh a page

In Selenium, is there an idiomatic way to refresh a page if a condition is False after a given timeout? For example,

  elem1 = WebDriverWait(driver, 60).until(EC.presence_of_element_located((By.CLASS_NAME, "some-class")))

If elem1 is still not present after 60 seconds, how do I refresh a page and start waiting over again?

Upvotes: 2

Views: 1852

Answers (2)

Dušan Maďar
Dušan Maďar

Reputation: 9919

Reload the site when NoSuchElementException occurs. I would suggest doing this in combination with implicitly_wait.

Also, using find_element_by_class_name would make the code less verbose and perhaps more readable as well.

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException

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

# try 2 times
for _ in range(1, 3):
    try:
        elem1 = driver.find_element_by_class_name("some-class")
        break
    except NoSuchElementException:
        driver.refresh()
        continue
else:
   # handle cases when element was not found

Upvotes: 4

Steve
Steve

Reputation: 976

If the WebDriverWait time is exceeded then it will throw a TimeoutException. Put the wait in a for loop with the try:...except: around it, add a delay in the except: clause. If no exception occurs then the page has loaded and you can break out of the for loop.

Upvotes: 1

Related Questions