StaleElementReferenceException on Python Selenium

后端 未结 9 2073
孤独总比滥情好
孤独总比滥情好 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:56

    Selenium Support Explicit and Implicit Waits. If you think waiting for certain amount of time is enough for your page to be loaded, use:

    driver.implicitly_wait(secs)
    

    but if you want to wait for a special event (e.g. waiting for a particular element to be loaded) you can do something like:

    from selenium.webdriver.support.ui import WebDriverWait
    ...
    ...
    def find(driver):
        element = driver.find_elements_by_id("data")
        if element:
            return element
        else:
            return False
    element = WebDriverWait(driver, secs).until(find)
    
    0 讨论(0)
  • 2020-11-27 14:04

    In my case, the problem

    stale element reference: element is not attached to the page document

    was because I tried to use actions.move_to_element(element).perform() on actions that created from old Selenium tab.

    So the solution is to create new actions instance after opening new tab:

    actions = ActionChains(browser)
    actions.move_to_element(element).perform()
    
    0 讨论(0)
  • 2020-11-27 14:05
    >>>Stale Exceptions can be handled using **StaleElementReferenceException** to continue the for loop execution.  
    
    from selenium.common import exceptions  
    
    # and customize your code of for loop as:  
    
    for i in range(0, 22):  
       try:  
            u = driver.find_elements_by_id("data")  
            text = u[0].get_attribute("innerHTML")  
            driver.find_elements_by_class_name("aclassname")[0].click()  
       except exceptions.StaleElementReferenceException,e:
            print(e)
            pass  
    

    Note: Python 3+ : replace exceptions.StaleElementReferenceException,e -> exceptions.StaleElementReferenceException as e

    0 讨论(0)
提交回复
热议问题