Anthony Nunez
Anthony Nunez

Reputation: 21

Keep refreshing page until element is clickable?

I am currently attempting to get my code to keep refreshing the page until a specific element on the website becomes clickable. Sample code is provided below:

lolSize = False
           

while not lolSize:
      try:
          if size.is_enabled():
               driver.execute_script("arguments[0].click();", size)
               lolSize = True
      except:
          time.sleep(1)
          driver.refresh()
        
        

Now if I put a value that is clickable at the exact moment of running the code, it works just fine. However, if a value that isn't clickable at the moment is used, the page does not refresh at all. Apologies if something rudimentary is incorrect with my code, I'm very much a novice in Python. Any help is appreciated, and if you need clarification regarding my issue, don't hesitate to ask! Thank you! :)

Upvotes: 1

Views: 470

Answers (2)

Nic Laforge
Nic Laforge

Reputation: 1876

You must handle the else condition of your if statement

while not lolSize:
      try:
          assert size.is_enabled()
          driver.execute_script("arguments[0].click();", size)
          lolSize = True
      except:
          time.sleep(1)
          driver.refresh()

The assert will raise an exception if it is not true and refresh will occur in the exception handler code.

Also, I believe with the code provided, upon refresh the is_enabled() code will always raise an exception. You need to retrieve the size element each refresh to not have a staleElementException. Such exception will loop your code with driver.refresh() each time.

UPDATE To ensure there is no element clickable, use the WebDriverWait to get time to find the element

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
 
timeout_in_sec = 5. # how much time to check for a clickable element
wait = WebDriverWait(driver, timeout_in_sec)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'yourCssPath')))

With code updated that gives:

wait = WebDriverWait(driver, timeout_in_sec)

while not lolSize:
      try:
          size = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'yourCssPath')))
          driver.execute_script("arguments[0].click();", size)
          lolSize = True
      except:
          time.sleep(1)
          driver.refresh()

Note that (By.CSS_SELECTOR, 'yourCssPath') needs to match the way you previously found size

Upvotes: 2

Mike Sigelakis
Mike Sigelakis

Reputation: 23

My idea for this problem would be like that :

while True: 
   try: 
      driver.execute_script("arguments[0].click();")
      break 
   except: 
          time.sleep(1)
          driver.refresh()      

Upvotes: 1

Related Questions