0

I am trying to wait for the loading spinner to finish loading and then perform some operation

My Code looks like

try:
    while driver.find_element(By.CSS_SELECTOR, "div.content-container div.content-element-container > div.loading-container").is_displayed()  == True:
    time.sleep(10) 
    driver.refresh()
    if count > 3:
         print("Could not fetch content")
         exit(1)
    count += 1
except Exception as e:
         print(str(e))

the reason for driver refresh is because of signal-r. For some reason the i do not get the data and the load spinner keeps on loading and then prints "Could Not fetch content").

If I refresh the page then I get NoSuchElementException. What would be the best way to handle such a scenario?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • When you use is_displayed() Selenium first tries to find the element and then checks if it's displayed. If it cannot, you will get NoSuchElementException. It is better to use Selenium Expectedconditions to wait for an element to be displayed. Let me know if you need an example. – JD308 Aug 02 '22 at 22:07

1 Answers1

0

This locator strategy:

(By.CSS_SELECTOR, "div.content-container div.content-element-container > div.loading-container")

represents the loading spinner / loader element. So on every refresh() the loader element will resurface again and again.


Solution

An elegant approach to get past the loading spinner will be to induce WebDriverWait for the invisibility_of_element_located() and you can use either of the following locator strategies:

  • Using CSS_SELECTOR:

    WebDriverWait(driver, 30).until(EC.invisibility_of_element_located((By.CSS_SELECTOR, "div.content-container div.content-element-container > div.loading-container")))
    
  • Using XPATH:

    WebDriverWait(driver, 30).until(EC.invisibility_of_element_located((By.XPATH, "//div[@class='content-container']//div[@class='content-element-container']/div[@class='loading-container']")))
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352