Home > Back-end >  How to handle Selenium when is_displayed attribute throws ElementNotFoundException error when page i
How to handle Selenium when is_displayed attribute throws ElementNotFoundException error when page i

Time:08-04

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?

CodePudding user response:

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
    
  • Related