StaleElementReferenceException on Python Selenium

后端 未结 9 2110
孤独总比滥情好
孤独总比滥情好 2020-11-27 13:28

I am getting the following error while using Selenium in python:

selenium.common.exceptions.StaleElementReferenceException: Message: u\'stale element referen         


        
9条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 13:49

    When webpage got refreshed or switched back from different window or form and trying to access an element user will get staleelementexception.

    Use webdriverwait in try --except block with for loop: EX :

    Code in which I got staleelementexception :


    driver.find_element_by_id(tc.value).click()
    

    driver.find_element_by_xpath("xpath").click()


    Fix :

    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    driver.find_element_by_id(tc.value).click()
    for i in range(4):
       try:
            run_test = WebDriverWait(driver, 120).until( \
            EC.presence_of_element_located((By.XPATH, "xpath")))
            run_test.click()
            break
       except StaleElementReferenceException as e:
            raise e
    

提交回复
热议问题