Wait until loader disappears python selenium

后端 未结 3 1859
终归单人心
终归单人心 2021-01-01 18:19
Loading
相关标签:
3条回答
  • 2021-01-01 18:52

    The following code creates an infinite loop until the element disappears:

    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.common.exceptions import TimeoutException
    
    while True:
            try:
                WebDriverWait(driver, 1).until(EC.presence_of_element_located((By.XPATH, 'your_xpath')))
            except TimeoutException:
                break
    
    0 讨论(0)
  • 2021-01-01 18:53

    Use expected condition : invisibility_of_element_located

    This works fine for me.

    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.support.wait import WebDriverWait
    
    
    WebDriverWait(driver, timeout).until(EC.invisibility_of_element_located((By.ID, "loader-mid")))
    
    0 讨论(0)
  • 2021-01-01 18:57

    Reiterated your answer (with some error handling) to make it easier for people to find the solution :)

    Importing required classes:

    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.support.wait import WebDriverWait
    

    Configuration variables:

    SHORT_TIMEOUT  = 5   # give enough time for the loading element to appear
    LONG_TIMEOUT = 30  # give enough time for loading to finish
    LOADING_ELEMENT_XPATH = '//*[@id="xPath"]/xPath/To/The/Loading/Element'
    

    Code solution:

    try:
        # wait for loading element to appear
        # - required to prevent prematurely checking if element
        #   has disappeared, before it has had a chance to appear
        WebDriverWait(driver, SHORT_TIMEOUT
            ).until(EC.presence_of_element_located((By.XPATH, LOADING_ELEMENT_XPATH)))
    
        # then wait for the element to disappear
        WebDriverWait(driver, LONG_TIMEOUT
            ).until_not(EC.presence_of_element_located((By.XPATH, LOADING_ELEMENT_XPATH)))
    
    except TimeoutException:
        # if timeout exception was raised - it may be safe to 
        # assume loading has finished, however this may not 
        # always be the case, use with caution, otherwise handle
        # appropriately.
        pass 
    
    0 讨论(0)
提交回复
热议问题